RPG attributes generator: Difference between revisions
Added Easylang
(Added Easylang) |
|||
(74 intermediate revisions by 36 users not shown) | |||
Line 1:
{{task}}
[[Category:Simple]]
'''RPG''' = <u>R</u>ole <u>P</u>laying <u>G</u>ame.
You're running a tabletop RPG, and your players are creating characters.
Line 16 ⟶ 20:
However, this can require a lot of manual dice rolling. A programatic solution would be much faster.
;Task:
Write a program that:
# Generates 4 random, whole values between 1 and 6.
Line 28 ⟶ 32:
* At least 2 of the values must be 15 or more.
<p></p>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">random:seed(Int(Time().unix_time()))
V total = 0
V count = 0
[Int] attributes
L total < 75 | count < 2
attributes = (0..5).map(attribute -> (sum(sorted((0..3).map(roll -> random:(1 .. 6)))[1..])))
L(attribute) attributes
I attribute >= 15
count++
total = sum(attributes)
print(total‘ ’attributes)</syntaxhighlight>
{{out}}
<pre>
76 [13, 13, 11, 14, 8, 17]
</pre>
=={{header|8086 Assembly}}==
<
cpu 8086
putch: equ 2h
Line 119 ⟶ 147:
section .bss
rnddat: resb 4 ; RNG state
attrs: resb 6 ; Rolled attributes</
{{out}}
Line 134 ⟶ 162:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program rpg64.s */
Line 370 ⟶ 398:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{Output}}
<pre>
Line 382 ⟶ 410:
Total = 83
Values above 15 = 2
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">TYPE Result=[BYTE success,sum,highCount]
BYTE FUNC GenerateAttrib()
BYTE i,v,min,sum
min=255 sum=0
FOR i=0 TO 3
DO
v=Rand(6)+1
IF v<min THEN
min=v
FI
sum==+v
OD
RETURN (sum-min)
PROC Generate(BYTE ARRAY a BYTE len Result POINTER res)
BYTE i,v,count
res.highCount=0 res.sum=0
FOR i=0 TO len-1
DO
v=GenerateAttrib()
IF v>=15 THEN
res.highCount==+1
FI
res.sum==+v
a(i)=v
OD
IF res.highCount<2 OR res.sum<75 THEN
res.success=0
ELSE
res.success=1
FI
RETURN
PROC Main()
DEFINE count="6"
BYTE ARRAY a(count)
Result res
BYTE i
res.success=0
WHILE res.success=0
DO
Generate(a,count,res)
Print("attribs: ")
FOR i=0 TO count-1
DO
PrintB(a(i))
IF i<count-1 THEN
Put(',)
FI
OD
PrintF(" sum=%B highCount=%B ",res.sum,res.highCount)
IF res.success THEN
PrintE("success")
ELSE
PrintE("failed")
FI
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/RPG_attributes_generator.png Screenshot from Atari 8-bit computer]
<pre>
attribs: 13,12,13,13,14,16 sum=81 highCount=1 failed
attribs: 10,10,15,9,16,8 sum=68 highCount=2 failed
attribs: 14,10,7,9,12,12 sum=64 highCount=0 failed
attribs: 12,13,16,16,18,16 sum=91 highCount=4 success
</pre>
=={{header|ALGOL 68}}==
{{Trans|Action!}}
<syntaxhighlight lang="algol68">BEGIN # RPG attributes generator #
INT attrib count = 6;
MODE RESULT = STRUCT( BOOL success, INT sum, high count, [ 1 : attrib count ]INT a );
PROC generate attrib = INT:
BEGIN
INT min := 255, sum := 0;
FOR i FROM 0 TO 3 DO
INT v = ENTIER( next random * 6 ) + 1;
IF v < min THEN
min := v
FI;
sum +:= v
OD;
sum - min
END # generate attrib #;
PROC generate = ( REF RESULT res )VOID:
BEGIN
high count OF res := 0;
sum OF res := 0;
FOR i FROM LWB a OF res TO UPB a OF res DO
INT v = generate attrib;
IF v >= 15 THEN
high count OF res +:= 1
FI;
sum OF res +:= v;
( a OF res )[ i ] := v
OD;
success OF res := ( high count OF res >= 2 AND sum OF res >= 75 )
END # generate # ;
RESULT res;
success OF res := FALSE;
WHILE NOT success OF res DO
generate( res );
print( ( "attribs: " ) );
FOR i FROM LWB a OF res TO UPB a OF res DO
print( ( whole( ( a OF res )[ i ], 0 ) ) );
IF i < UPB a OF res THEN
print( ( " " ) )
FI
OD;
print( ( " sum=", whole( sum OF res, 0 )
, " highCount=", whole( high count OF res, 0 )
, " ", IF success OF res THEN "success" ELSE "failed" FI
, newline
)
)
OD
END</syntaxhighlight>
{{out}}
<pre>
attribs: 12 7 15 12 7 13 sum=66 highCount=1 failed
attribs: 10 10 11 13 9 9 sum=62 highCount=0 failed
attribs: 10 13 10 15 10 11 sum=69 highCount=1 failed
attribs: 10 16 15 11 16 8 sum=76 highCount=3 success
</pre>
Line 387 ⟶ 549:
{{works with|Dyalog APL}}
<
{{out}}
<pre> roll''
roll''
18 14
roll''
roll''
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 728 ⟶ 888:
bx lr
</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">vals: []
while [or? 75 > sum vals
2 > size select vals => [&>=15]] [
vals: new []
while [6 > size vals][
rands: new map 1..4 => [random 1 6]
remove 'rands .once (min rands)
'vals ++ sum rands
]
]
print ["values:" vals ]
print ["with sum:" sum vals]</syntaxhighlight>
=={{header|Atari BASIC}}==
{{trans|Commodore BASIC}}
<syntaxhighlight lang="basic">100 REM RPG character generator
110 DIM AT(5)
120 DIM AT$(18)
130 AT$="StrDexConIntWisCha"
140 PT=0:SA=0
150 PRINT CHR$(125);CHR$(29);CHR$(31);"Rolling..."
160 FOR AI=0 TO 5
170 DT=0:MI=6:REM dice total, min die
180 FOR I=0 TO 3
190 D=INT(RND(1)*6)+1
200 DT=DT+D
210 IF D<MI THEN MI=D
220 NEXT I
230 DT=DT-MI
240 AT(AI)=DT
250 PT=PT+DT
260 IF DT>=15 THEN SA=SA+1
270 NEXT AI
280 IF PT<75 OR SA<2 THEN 140
290 PRINT CHR$(125);"Character Attributes:"
300 PRINT
310 FOR AI=0 TO 5
315 POSITION 10,AI+2
320 PRINT AT$(AI*3+1,AI*3+3);":";
330 POSITION 16-INT(AT(AI)/10),AI+2
340 PRINT AT(AI)
350 NEXT AI
360 POSITION 8,9
370 PRINT "Total: ";PT
380 PRINT
390 PRINT "Do you accept? ";
400 OPEN #1,4,0,"K:"
410 GET #1,K
420 IF K<>78 AND K<>89 THEN 410
430 PRINT CHR$(K)
440 CLOSE #1
450 IF K=78 THEN 140
460 POSITION 0,13
470 PRINT "Excellent. Good luck on your adventure!"</syntaxhighlight>
{{Out}}
<pre> Character Attributes:
Str: 17
Dex: 15
Con: 13
Int: 11
Wis: 11
Cha: 14
Total: 81
Do you accept? Y
Excellent. Good luck on your adventure!
Ready
</pre>
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="freebasic">function min(a, b)
if a < b then return a else return b
end function
function d6()
#simulates a marked regular hexahedron coming to rest on a plane
return 1 + int(rand * 6)
end function
function roll_stat()
#rolls four dice, returns the sum of the three highest
a = d6() : b = d6() : c = d6() : d = d6()
return a + b + c + d - min(min(a, b), min(c, d))
end function
arraybase 1
dim statnames$ = {"STR", "CON", "DEX", "INT", "WIS", "CHA"}
dim stat(6)
acceptable = false
do
sum = 0 : n15 = 0
for i = 1 to 6
stat[i] = roll_stat()
sum += stat[i]
if stat[i] >= 15 then n15 += 1
next i
if sum >= 75 and n15 >= 2 then acceptable = true
until acceptable
for i = 1 to 6
print statnames$[i]; ": "; stat[i]
next i
print "-------"
print "TOT: "; sum
end</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
=={{header|BQN}}==
Slightly different from the APL solution primarily due to builtin differences.
<syntaxhighlight lang="bqn"> _while_←{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
(2-modifier block)
Roll←{𝕊:{𝕊:((+´-⌊´)1+4⊸•rand.Range)¨6⥊6}_while_{(75>+´𝕩)∨2>+´15≤𝕩}⟨⟩}
(function block)
Roll@
⟨ 11 16 12 10 16 13 ⟩</syntaxhighlight>
=={{header|C}}==
{{trans|Go}}
<
#include <stdlib.h>
#include <time.h>
Line 775 ⟶ 1,061:
}
return 0;
}</
{{out}}
Line 788 ⟶ 1,074:
=={{header|C sharp|C#}}==
{{trans|Visual Basic .NET}}
<
using System.Collections.Generic;
using System.Linq;
Line 819 ⟶ 1,105:
} while (!good);
}
}</
{{out}}
sample outputs:
Line 828 ⟶ 1,114:
=={{header|C++}}==
GCC 4.9.2, unoptimised.
<
#include <ctime>
#include <iostream>
Line 879 ⟶ 1,165:
return 0;
}</
{{out}}
Sample run:
Line 888 ⟶ 1,174:
=={{header|Caché ObjectScript}}==
<syntaxhighlight lang="caché objectscript">RPGGEN
set attr = $lb("") ; empty list to start
write "Rules:",!,"1.) Total of 6 attributes must be at least 75.",!,"2.) At least two scores must be 15 or more.",!
Line 933 ⟶ 1,219:
} while (result '= 3)
quit</
{{out}}<pre>
Line 946 ⟶ 1,232:
Total 80 and 2 attributes >=15 are sufficient.
</pre>
=={{header|CLU}}==
<syntaxhighlight lang="clu">% This program needs to be merged with PCLU's "misc" library
% to use the random number generator.
%
% pclu -merge $CLUHOME/lib/misc.lib -compile rpg_gen.clu
% Seed the random number generator with the current time
init_rng = proc ()
d: date := now()
seed: int := ((d.hour*60) + d.minute)*60 + d.second
random$seed(seed)
end init_rng
character = cluster is generate
rep = null
% Roll a die
roll_die = proc () returns (int)
return (1 + random$next(6))
end roll_die
% Roll four dice and get the sum of the highest three rolls
roll_four_times = proc () returns (int)
lowest: int := 7 % higher than any dice roll
sum: int := 0
for i: int in int$from_to(1,4) do
roll: int := roll_die()
sum := sum + roll
if roll < lowest then lowest := roll end
end
return (sum - lowest)
end roll_four_times
% Try to generate a character by rolling six values
try_generate = proc () returns (sequence[int])
rolls: sequence[int] := sequence[int]$[]
for i: int in int$from_to(1,6) do
rolls := sequence[int]$addh(rolls, roll_four_times())
end
return (rolls)
end try_generate
% See if a character is valid
valid = proc (c: sequence[int]) returns (bool)
total: int := 0
at_least_15: int := 0
for i: int in sequence[int]$elements(c) do
total := total + i
if i >= 15 then at_least_15 := at_least_15 + 1 end
end
return (total >= 75 & at_least_15 >= 2)
end valid
% Generate a character
generate = proc () returns (sequence[int])
while true do
c: sequence[int] := try_generate()
if valid(c) then return(c) end
end
end generate
end character
% Generate a character and display the six values
start_up = proc ()
po: stream := stream$primary_output()
init_rng()
hero: sequence[int] := character$generate()
for stat: int in sequence[int]$elements(hero) do
stream$putright(po, int$unparse(stat), 4)
end
end start_up</syntaxhighlight>
{{out}}
<pre>$ ./rpg_gen
14 9 12 15 13 16
$ ./rpg_gen
11 15 14 17 13 13
$ ./rpg_gen
10 16 10 12 16 16
$ ./rpg_gen
16 11 16 11 14 13
$ ./rpg_gen
16 7 14 15 13 10</pre>
=={{header|Commodore BASIC}}==
Except for screen control codes, this is generic enough it could be used for many other 8-bit interpreted BASICs as well. (Applesoft, ZX Spectrum, etc.). Should work on all Commodore models. (Adjustment for screen width may be necessary on VIC-20.)
<syntaxhighlight lang="gwbasic">100 rem rpg character roller
110 rem rosetta code - commodore basic
120 dim di(3):rem dice
130 dim at(5),at$(5):rem attributes as follows:
140 at$(0)="Strength"
150 at$(1)="Dexterity"
160 at$(2)="Constitution"
170 at$(3)="Intelligence"
180 at$(4)="Wisdom"
190 at$(5)="Charisma"
200 pt=0:sa=0:rem points total and number of strong attributes (15+)
210 print chr$(147);chr$(14);chr$(29);chr$(17);"Rolling..."
220 for ai=0 to 5:rem attribute index
230 for i=0 to 3:di(i)=int(rnd(.)*6)+1:next i
240 gosub 450
250 dt=0:rem dice total
260 for i=0 to 2:dt=dt+di(i):next i:rem take top 3
270 at(ai)=dt:pt=pt+dt
280 if dt>=15 then sa=sa+1
290 next ai
300 if pt<75 or sa<2 then goto 200
310 print chr$(147);"Character Attributes:"
320 print
330 for ai=0 to 5
340 print spc(13-len(at$(ai)));at$(ai);":";tab(14);at(ai)
350 next ai
360 print
370 print " Total:";tab(14);pt
380 print
390 print "Do you accept? ";
400 get k$:if k$<>"y" and k$<>"n" then 400
410 print k$
420 if k$="n" then goto 200
430 print:print "Excellent. Good luck on your adventure!"
440 end
450 rem "sort" dice - really just put smallest one last
460 for x=0 to 2
470 if di(x)<di(x+1) then t=di(x):di(x)=di(x+1):di(x+1)=t
480 next x
490 return</syntaxhighlight>
{{out}}
<nowiki>
ready.
run
Rolling...
Character Attributes:
Strength: 8
Dexterity: 11
Constitution: 16
Intelligence: 14
Wisdom: 12
Charisma: 15
Total: 76
Do you accept? n
Rolling...
Character Attributes:
Strength: 16
Dexterity: 15
Constitution: 8
Intelligence: 15
Wisdom: 11
Charisma: 15
Total: 80
Do you accept? y
Excellent. Good luck on your adventure!
ready.
█
</nowiki>
=={{header|Common Lisp}}==
===Mapping functions===
<syntaxhighlight lang="lisp">
(defpackage :rpg-generator
(:use :cl)
(:export :generate))
(in-package :rpg-generator)
(defun sufficient-scores-p (scores)
(and (>= (apply #'+ scores) 75)
(>= (count-if #'(lambda (n) (>= n 15)) scores) 2)))
(defun gen-score ()
(apply #'+ (rest (sort (loop repeat 4 collect (1+ (random 6))) #'<))))
(defun generate ()
(loop for scores = (loop repeat 6 collect (gen-score))
until (sufficient-scores-p scores)
finally (format t "Scores: ~A~%" scores)
(format t "Total: ~A~%" (apply #'+ scores))
(format t ">= 15: ~A~%" (count-if (lambda (n) (>= n 15)) scores))
(return scores)))
</syntaxhighlight>
=== Loop macro ===
''Draft''
==== Note ====
See [https://gigamonkeys.com/book/loop-for-black-belts.html Loop for Black Belts ]
==== Program ====
<syntaxhighlight lang="lisp">;; 22.11.07 Draft
(defun score-jet-des ()
(loop :for resultat = (+ (random 6) 1)
:repeat 4
:sum resultat :into total
:minimize resultat :into minimum
:finally (return (- total minimum))))
(defun calcule-attributs-personnage ()
(loop named a
:do (loop :for score = (score-jet-des)
:repeat 6
:collect score :into scores
:sum score :into total
:count (>= score 15) :into frequence
:finally (when (and (>= total 75) (>= frequence 2))
(return-from a (values scores total))))))
</syntaxhighlight>
==== Execution ====
<pre>
(multiple-value-bind (scores total)
(calcule-attributs-personnage)
(list scores total))
</pre>
{{out}}
<pre>
((16 9 15 12 14 14) 80)
</pre>
''cyril nocton (cyril.nocton@gmail.com) w/ google translate''
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
include "argv.coh";
# There is no random number generator in the standard library (yet?)
# There is also no canonical source of randomness, and indeed,
# on some target platforms (like CP/M) there is no guaranteed
# source of randomness at all. Therefore, I implement the "X ABC"
# random number generator, and ask for a seed on the command line.
record RandState is
x @at(0): uint8;
a @at(1): uint8;
b @at(2): uint8;
c @at(3): uint8;
end record;
sub RandByte(s: [RandState]): (r: uint8) is
s.x := s.x + 1;
s.a := s.a ^ s.c ^ s.x;
s.b := s.b + s.a;
s.c := s.c + (s.b >> 1) ^ s.a;
r := s.c;
end sub;
# Roll a d6
typedef D6 is int(1, 6);
sub Roll(s: [RandState]): (r: D6) is
var x: uint8;
loop
x := RandByte(s) & 7;
if x < 6 then break; end if;
end loop;
r := x + 1;
end sub;
# Roll 4 D6es and get the sum of the 3 highest
sub Roll4(s: [RandState]): (r: uint8) is
r := 0;
var lowest: uint8 := 0;
var n: uint8 := 4;
while n > 0 loop
var roll := Roll(s);
r := r + roll;
if lowest > roll then
lowest := roll;
end if;
n := n - 1;
end loop;
r := r - lowest;
end sub;
# Read random seed from command line
var randState: RandState;
ArgvInit();
var argmt := ArgvNext();
if argmt == (0 as [uint8]) then
print("Please give random seed on command line.\n");
ExitWithError();
end if;
([&randState as [int32]], argmt) := AToI(argmt);
var total: uint8;
var attrs: uint8[6];
var i: @indexof attrs;
loop
var at15: uint8 := 0;
i := 0;
total := 0;
# generate 6 attributes
while i < 6 loop
attrs[i] := Roll4(&randState);
total := total + attrs[i];
# count how many are higher than or equal to 15
if attrs[i] >= 15 then
at15 := at15 + 1;
end if;
i := i + 1;
end loop;
# if the requirements are met, then stop
if total >= 75 and at15 >= 2 then
break;
end if;
end loop;
# Show the generated values
print("Attributes: ");
i := 0;
while i < 6 loop
print_i8(attrs[i]);
print_char(' ');
i := i + 1;
end loop;
print("\nTotal: ");
print_i8(total);
print_nl();</syntaxhighlight>
{{out}}
<pre>$ ./rpgroll.386 123
Attributes: 14 15 23 13 18 12
Total: 95
$ ./rpgroll.386 124
Attributes: 10 17 11 12 14 17
Total: 81
$ ./rpgroll.386 125
Attributes: 6 21 13 14 23 19
Total: 96</pre>
=={{header|Crystal}}==
<
dices = Array(Int32).new(4) { rand(1..6) }
dices.sum - dices.min
Line 963 ⟶ 1,596:
stats = roll_character
puts "stats: #{stats}, sum is #{stats.sum}"
end</
sample output:
Line 976 ⟶ 1,609:
stats: [17, 13, 11, 10, 14, 16], sum is 81
stats: [11, 16, 11, 13, 15, 16], sum is 82</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Generics.Collections}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
program RPG_Attributes_Generator;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Generics.Collections;
type
TListOfInt = class(TList<Integer>)
public
function Sum: Integer;
function FindAll(func: Tfunc<Integer, Boolean>): TListOfInt;
function Join(const sep: string): string;
end;
{ TListOfInt }
function TListOfInt.FindAll(func: Tfunc<Integer, Boolean>): TListOfInt;
var
Item: Integer;
begin
Result := TListOfInt.Create;
if Assigned(func) then
for Item in self do
if func(Item) then
Result.Add(Item);
end;
function TListOfInt.Join(const sep: string): string;
var
Item: Integer;
begin
Result := '';
for Item in self do
if Result.IsEmpty then
Result := Item.ToString
else
Result := Result + sep + Item.ToString;
end;
function TListOfInt.Sum: Integer;
var
Item: Integer;
begin
Result := 0;
for Item in self do
Inc(Result, Item);
end;
function GetThree(n: integer): TListOfInt;
var
i: Integer;
begin
Randomize;
Result := TListOfInt.Create;
for i := 0 to 3 do
Result.Add(Random(n) + 1);
Result.Sort;
Result.Delete(0);
end;
function GetSix(): TListOfInt;
var
i: Integer;
tmp: TListOfInt;
begin
Result := TListOfInt.Create;
for i := 0 to 5 do
begin
tmp := GetThree(6);
Result.Add(tmp.Sum);
tmp.Free;
end;
end;
const
GOOD_STR: array[Boolean] of string = ('low', 'good');
SUCCESS_STR: array[Boolean] of string = ('failure', 'success');
var
good: Boolean;
gs, hvcList: TListOfInt;
gss, hvc: Integer;
begin
good := false;
repeat
gs := GetSix();
gss := gs.Sum;
hvcList := gs.FindAll(
function(x: Integer): Boolean
begin
result := x > 14;
end);
hvc := hvcList.Count;
hvcList.Free;
Write(Format('Attribs: %s, sum=%d, (%s sum, high vals=%d)', [gs.Join(', '),
gss, GOOD_STR[gss >= 75], hvc]));
good := (gss >= 75) and (hvc > 1);
Writeln(' - ', SUCCESS_STR[good]);
gs.Free;
until good;
Readln;
end.
</syntaxhighlight>
{{out}}
<pre>
Attribs: 8, 15, 15, 16, 14, 10, sum=78, (good sum, high vals=3) - success
</pre>
=={{header|Dyalect}}==
{{trans|C#}}
<
var g3 = []
for i in 0..33 {
g3.
}
g3.
g3.
g3
}
func getSix() {
var g6 = []
for i in 0..5 {
g6.
}
g6
}
func Array.
var acc = 0
for x in this {
Line 1,004 ⟶ 1,762:
acc
}
func Array.
for x in this when pred(x) {
yield x
Line 1,012 ⟶ 1,770:
var good = false
while !good {
var gs = getSix()
var gss = gs.
var hvc = gs.
print("attribs: \
print("(\(gl)
good = gs.Sum() >= 75 && hvc > 1
print(" - " + (good ? "success" : "failure"))
}</syntaxhighlight>
{{out}}
Line 1,027 ⟶ 1,787:
=={{header|EasyLang}}==
{{trans|BASIC256}}
<syntaxhighlight>
func rollstat .
for i to 4
h = randint 6
s += h
min = lower min h
.
return s - min
.
state$[] = [ "STR" "CON" "DEX" "INT" "WIS" "CHA" ]
len stat[] 6
repeat
for i
.
until
.
for i to 6
.
print "-------"
print "TOT: " & sum
</syntaxhighlight>
{{out}}
<pre>
STR: 13
CON: 11
DEX: 16
INT: 8
WIS: 17
CHA: 18
-------
TOT: 83
</pre>
=={{header|Factor}}==
{{Works with|Factor|0.98}}
<
math.statistics qw sequences ;
IN: rosetta-code.rpg-attributes-generator
Line 1,076 ⟶ 1,847:
: generate-valid-stats ( -- seq )
: stats-info ( seq -- )
Line 1,086 ⟶ 1,857:
[ "%s: %d\n" printf ] 2each nl stats-info ;
MAIN: main</
{{out}}
<pre>
Line 1,099 ⟶ 1,870:
# of attributes >= 15: 2
</pre>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">#define min(a, b) iif(a < b, a, b)
function d6() as integer
'simulates a marked regular hexahedron coming to rest on a plane
return 1+int(rnd*6)
end function
function roll_stat() as integer
'rolls four dice, returns the sum of the three highest
dim as integer a=d6(), b=d6(), c=d6(), d=d6()
return a + b + c + d - min( min(a, b), min(c, d) )
end function
dim as string*3 statnames(1 to 6) = {"STR", "CON", "DEX", "INT", "WIS", "CHA"}
dim as integer stat(1 to 6), n15, sum
dim as boolean acceptable = false
randomize timer
do
sum = 0
n15 = 0
for i as integer = 1 to 6
stat(i) = roll_stat()
sum = sum + stat(i)
if stat(i)>=15 then n15 += 1
next i
if sum>=75 and n15 >=2 then acceptable = true
loop until acceptable
for i as integer = 1 to 6
print using "&: ##";statnames(i);stat(i)
next i
print "--------"
print using "TOT: ##";sum</syntaxhighlight>
{{out}}<pre>STR: 14
CON: 11
DEX: 15
INT: 14
WIS: 13
CHA: 15
--------
TOT: 82
</pre>
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">01.10 S T=0
01.20 F X=1,6;D 4;S AT(X)=S3;S T=T+S3
01.30 I (T-75)1.1
01.40 S K=0;F X=1,6;D 2
01.50 I (K-2)1.1
01.55 T "STR DEX CON INT WIS CHA TOTAL",!
01.60 F X=1,6;T %2,AT(X)," "
01.70 T T,!
01.80 Q
02.10 I (AT(X)-15)2.3,2.2,2.2
02.20 S K=K+1
02.30 R
04.01 C--ROLL 4 D6ES AND GIVE SUM OF LARGEST 3
04.10 S XS=7;S S3=0;S XN=4
04.20 D 6;S S3=S3+A;I (XS-A)4.4,4.4,4.3
04.30 S XS=A
04.40 S XN=XN-1;I (XN),4.5,4.2
04.50 S S3=S3-XS
06.01 C--ROLL A D6
06.10 S A=FRAN()*10;S A=A-FITR(A)
06.20 S A=1+FITR(A*6)</syntaxhighlight>
{{out}}
<pre>*G
STR DEX CON INT WIS CHA TOTAL
= 16 = 12 = 14 = 8 = 15 = 12 = 77
*G
STR DEX CON INT WIS CHA TOTAL
= 9 = 13 = 8 = 17 = 13 = 16 = 76
*G
STR DEX CON INT WIS CHA TOTAL
= 12 = 14 = 7 = 15 = 12 = 17 = 77
*G
STR DEX CON INT WIS CHA TOTAL
= 11 = 16 = 16 = 11 = 14 = 10 = 78
*G
STR DEX CON INT WIS CHA TOTAL
= 15 = 15 = 13 = 13 = 11 = 13 = 80
*G
STR DEX CON INT WIS CHA TOTAL
= 16 = 9 = 16 = 9 = 11 = 14 = 75</pre>
=={{header|Forth}}==
{{works with|GNU Forth}}
{{libheader|random.fs}}
<syntaxhighlight lang="forth">require random.fs
: d6 ( -- roll ) 6 random 1 + ;
variable smallest
: genstat ( -- stat )
d6 dup smallest !
3 0 do
d6 dup smallest @ < if dup smallest ! then +
loop
smallest @ -
;
variable strong
variable total
: genstats ( -- cha wis int con dex str )
0 strong !
0 total !
6 0 do
genstat
dup 15 >= if strong @ 1 + strong ! then
dup total @ + total !
loop
total @ 75 < strong @ 2 < or if
drop drop drop drop drop drop
recurse
then
;
: roll ( -- )
genstats
." str:" . ." dex:" . ." con:" .
." int:" . ." wis:" . ." cha:" .
." (total:" total @ . 8 emit ." )"
;
utime drop seed !</syntaxhighlight>
{{Out}}
<pre>roll str:13 dex:15 con:14 int:8 wis:17 cha:10 (total:77) ok</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
_elements = 6
local fn min( a as long, b as long ) as long
long result
if ( a < b )
result = a : exit fn
else
result = b : exit fn
end if
end fn = result
local fn d6 as long
long result
result = 1 + int( rnd(_elements) )
end fn = result
local fn roll_stat as long
long result
long a = fn d6, b = fn d6, c = fn d6, d = fn d6
result = a + b + c + d - fn min( fn min( a, b ), fn min( c, d ) )
end fn = result
local fn DoIt
CFArrayRef statnames = @[@"Strength",@"Constitution",@"Dexterity",@"Intelligence",@"Wisdom",@"Charisma"]
long stat(_elements), n15, sum, i
BOOL acceptable = NO
randomize
do
sum = 0
n15 = 0
for i = 1 to _elements
stat(i) = fn roll_stat
sum = sum + stat(i)
if stat(i) >= 15 then n15++
next
if sum >= 75 and n15 >= 2 then acceptable = YES
until ( acceptable = YES )
for i = 1 to _elements
printf @"%12s %3ld", fn StringUTF8String( statnames[i -1] ), stat(i)
next
printf @"------------"
printf @"%13s %3ld", "Total:", sum
end fn
fn DoIt
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Strength 17
Constitution 11
Dexterity 18
Intelligence 12
Wisdom 19
Charisma 11
------------
Total: 88
</pre>
=={{header|Go}}==
<
import (
Line 1,146 ⟶ 2,118:
break
}
}</
{{out}}
Line 1,158 ⟶ 2,130:
=={{header|Haskell}}==
<
import System.Random (randomRIO)
import Data.Bool (bool)
import Data.List (sort)
Line 1,166 ⟶ 2,139:
discardUntil
(((&&) . (75 <) . sum) <*> ((2 <=) . length . filter (15 <=)))
(replicateM 6 $ sum . tail . sort <$> replicateM 4 (randomRIO (1, 6 :: Int)))
discardUntil :: ([Int] -> Bool) -> IO [Int] -> IO [Int]
discardUntil p throw = go
where
go
main :: IO ()
main = replicateM 10 character >>= mapM_ (print . (sum >>= (,)))</
{{Out}}
<pre>Sample computation:
Line 1,198 ⟶ 2,165:
=={{header|J}}==
'twould be more efficient to work with index origin 0, then increment the roll once at output.
<syntaxhighlight lang="j">
roll=:
massage=: +/ - <./
generate_attributes=: massage@:roll
Line 1,211 ⟶ 2,178:
NB. use: generate_character 'name'
generate_character=: (; (+/ ; ])@:([: generate_attributes@:show Until accept 0:))&>@:boxopen
</syntaxhighlight>
Line 1,244 ⟶ 2,211:
=={{header|Java}}==
<syntaxhighlight lang="java">import java.util.List;
import java.util.Random;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class Rpg {
private static final Random random = new Random();
public static int genAttribute() {
return random.ints(1, 6 + 1) // Throw dices between 1 and 6
.limit(4) // Do 5 throws
.sorted() // Sort them
.limit(3) // Take the top 3
.sum(); // Sum them
}
public static void main(String[] args) {
while (true) {
Stream.generate(Rpg::genAttribute) // Generate some stats
.collect(toList()); // Save them in an array
if (count >= 2
System.out.printf("The 6 random numbers generated are: %s\n", stats);
System.out.printf("Their sum is %s and %s of them are >= 15\n", sum, count);
}
}
}
}</syntaxhighlight>
{{Out}}
<pre>
The 6 random numbers generated are: [10, 18, 9, 15, 14, 14]
Their sum is 80 and 2 of them are >= 15
</pre>
=={{header|Javascript}}==
===Imperative===
<
const stats = {
total: 0,
Line 1,338 ⟶ 2,286:
${rolledCharacter.rolls.join(', ')}
Their sum is ${rolledCharacter.total} and ${rolledCharacter.rolls.filter(a => a >= 15).length} of them are >= 15`);</
{{out}}
Line 1,351 ⟶ 2,299:
===Functional===
{{Trans|Python}} (Functional composition version)
<
'use strict';
Line 1,474 ⟶ 2,422:
// MAIN ---
return main();
})();</
{{Out}}
A sample of 10 character attribute sets:
Line 1,487 ⟶ 2,435:
79 -> [15,15,11,17,12,9]
76 -> [14,12,9,15,15,11]</pre>
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq.'''
In this entry, /dev/random is used as a source of entropy,
via the invocation:
<pre>
< /dev/random tr -cd '0-9' | fold -w 1 | jq -Mcnr -f rgp-attributes.jq
</pre>
where rgp-attributes.jq is a file containing the jq program shown below.
'''The jq program'''
<syntaxhighlight lang=jq>
def count(s): reduce s as $x (0; .+1);
# Output: a PRN in range(0;$n) where $n is .
def prn:
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
# Output: [$four, $sum]
# where $four is an array of 4 pseudo-random integers between 1 and 6 inclusive,
# and $sum records the sum of the 3 largest values.
def generate_RPG:
[range(0; 4) | (1 + (7|prn) )] as $four
| [$four, ($four|sort|.[-3:]|add)];
# Input: $six as produced by [range(0;6) | generate_RPG]
# Determine if the following conditions are met:
# - the total of all 6 of the values at .[-1] is at least 75;
# - at least 2 of these values must be 15 or more.
def ok:
([.[][-1]] | add) as $sum
| $sum >= 75 and
count( (.[][1] >= 15) // empty) >= 2;
# First show [range(0;6) | generate_RPG]
# and then determine if it meets the "ok" condition;
# if not, repeat until a solution has been found.
def task:
[range(0;6) | generate_RPG] as $six
| ([$six[][-1]] | add) as $sum
| $six[], "Sum: \($sum)",
if $six | ok then "All done."
else "continuing search ...",
({}
| until(.emit;
[range(0;6) | generate_RPG] as $six
| ([$six[][-1]] | add) as $sum
| if $six | ok
then .emit = {$six, $sum}
else .
end).emit
| (.six[], "Sum: \(.sum)" ) )
end;
task
</syntaxhighlight>
{{Output}}
''Example of a run which only one round of throwing the four dice''
<pre>
[[7,7,1,1],15]
[[1,5,3,7],15]
[[5,3,2,1],10]
[[2,4,7,5],16]
[[7,4,2,7],18]
[[3,6,2,4],13]
Sum: 87
All done.
</pre>
''Example of a run requiring more than one round of throwing the four dice''
<pre>
[[6,6,1,3],15]
[[3,3,6,5],14]
[[7,2,7,5],19]
[[6,6,5,5],17]
[[5,7,3,4],16]
[[6,1,2,5],13]
Sum: 94
continuing search ...
[[7,7,2,7],21]
[[7,4,1,6],17]
[[7,3,3,1],13]
[[7,7,6,4],20]
[[2,3,6,5],14]
[[6,1,5,2],13]]
Sum: 98
</pre>
=={{header|Julia}}==
<
function rollRPGtoon()
Line 1,510 ⟶ 2,551:
rollRPGtoon()
rollRPGtoon()
</
New RPG character roll: [15, 16, 15, 11, 9, 15]. Sum is 81, and 4 are >= 15.
New RPG character roll: [12, 14, 15, 12, 10, 16]. Sum is 79, and 2 are >= 15.
Line 1,517 ⟶ 2,558:
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">import kotlin.random.Random
fun main() {
while (true) {
val values =
val rolls = generateSequence { 1 + Random.nextInt(6) }.take(4)
}
val vsum = values.sum()
val vcount = values.count { it >= 15 }
if (vsum < 75 || vcount < 2) continue
println("The 6 random numbers generated are: $values")
println(
break
}
}</
{{output}}
Sample run:
<pre>
The 6 random numbers generated are: [13, 14, 13, 15, 17, 8]
Their sum is 80 and 2 of them are >= 15
</pre>
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
# RPG attributes generator
# # Variables:
#
typeset -a attribs=( strength dexterity constitution intelligence wisdom charisma )
integer MINTOT=75 MIN15S=2
# # Functions:
#
# # Function _diceroll(sides, number, reportAs) - roll number of side-sided
# # dice, report (s)sum or (a)array (pseudo) of results
#
function _diceroll {
typeset _sides ; integer _sides=$1 # Number of sides of dice
typeset _numDice ; integer _numDice=$2 # Number of dice to roll
typeset _rep ; typeset -l -L1 _rep="$3" # Report type: (sum || array)
typeset _seed ; (( _seed = SECONDS / $$ )) ; _seed=${_seed#*\.}
typeset _i _sum ; integer _i _sum=0
typeset _arr ; typeset -a _arr
RANDOM=${_seed}
for (( _i=0; _i<_numDice; _i++ )); do
(( _arr[_i] = (RANDOM % _sides) + 1 ))
[[ ${_rep} == s ]] && (( _sum += _arr[_i] ))
done
if [[ ${_rep} == s ]]; then
echo ${_sum}
else
echo "${_arr[@]}"
fi
}
# # Function _sumarr(n arr) - Return the sum of the first n arr elements
#
function _sumarr {
typeset _n ; integer _n=$1
typeset _arr ; nameref _arr="$2"
typeset _i _sum ; integer _i _sum
for ((_i=0; _i<_n; _i++)); do
(( _sum+=_arr[_i] ))
done
echo ${_sum}
}
######
# main #
######
until (( total >= MINTOT )) && (( cnt15 >= MIN15S )); do
integer total=0 cnt15=0
unset attrval ; typeset -A attrval
for attr in ${attribs[*]}; do
unset darr ; typeset -a darr=( $(_diceroll 6 4 a) )
set -sK:nr -A darr
attrval[${attr}]=$(_sumarr 3 darr)
(( total += attrval[${attr}] ))
(( attrval[${attr}] > 14 )) && (( cnt15++ ))
done
done
for attr in ${attribs[*]}; do
printf "%12s: %2d\n" ${attr} ${attrval[${attr}]}
done
print "Attribute value total: ${total}"
print "Attribule count >= 15: ${cnt15}"
</syntaxhighlight>
{{out}}<pre>
strength: 11
dexterity: 14
constitution: 14
intelligence: 15
wisdom: 15
charisma: 12
Attribute value total: 81
Attribule count >= 15: 2 </pre>
=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
attributes is number list
i is number
attr is number
sum is number
count is number
procedure:
sub attribute
parameters:
result is number
local data:
min is number
n is number
i is number
procedure:
store 6 in min
for i from 0 to 4 step 1 do
get random in n
in n solve 6 * n + 1
floor n
add n and result in result
if n is less than min then
store n in min
end if
repeat
subtract min from result in result
end sub
create statement "get attribute in $" executing attribute
label generate-attributes
for i from 0 to 6 step 1 do
get attribute in attr
add attr and sum in sum
if attr is greater than 14 then
add count and 1 in count
end if
push attr to attributes
store 0 in attr
repeat
if sum is less than 75 or count is less than 2 then
display "Failed..." lf
store 0 in sum
store 0 in count
clear attributes
goto generate-attributes
end if
for each attr in attributes do
display attr " "
repeat
display lf "Sum: " sum lf ">14: " count lf
</syntaxhighlight>
{{out}}
<pre>
Failed...
Failed...
Failed...
Failed...
11 15 12 16 15 15
Sum: 84
>14: 4
</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">valid = False;
While[! valid,
try = Map[Total[TakeLargest[#, 3]] &,
RandomInteger[{1, 6}, {6, 4}]];
If[Total[try] > 75 && Count[try, _?(GreaterEqualThan[15])] >= 2,
valid = True;
]
]
{Total[try], try}</syntaxhighlight>
{{out}}
<pre>{78, {13, 15, 9, 13, 12, 16}}</pre>
=={{header|min}}==
{{works with|min|0.19.6}}
<
; Implement some general operators we'll need that aren't in the library.
Line 1,567 ⟶ 2,762:
(big (dup special?) () (pop big) () linrec) :stats ; Roll a set of big and special attributes.
stats puts "Total: " print! sum puts!</
{{out}}
<pre>
Line 1,575 ⟶ 2,770:
=={{header|MiniScript}}==
<
results = []
for i in range(0,3)
Line 1,601 ⟶ 2,796:
end while
print "Success!"
</syntaxhighlight>
{{out}}
<pre>Attribute values: 11, 13, 8, 10, 8, 10
Line 1,618 ⟶ 2,813:
Attributes total: 86
Success!</pre>
=={{header|Nim}}==
<syntaxhighlight lang="nim">
# Import "random" to get random numbers and "algorithm" to get sorting functions for arrays.
import random, algorithm
randomize()
proc diceFourRolls(): array[4, int] =
## Generates 4 random values between 1 and 6.
for i in 0 .. 3:
result[i] = rand(1..6)
proc sumRolls(rolls: array[4, int]): int =
## Save the sum of the 3 highest values rolled.
var sorted = rolls
sorted.sort()
# By sorting first and then starting the iteration on 1 instead of 0, the lowest number is discarded even if it is repeated.
for i in 1 .. 3:
result += sorted[i]
func twoFifteens(attr: var array[6, int]): bool =
attr.sort()
# Sorting implies than the second to last number is lesser than or equal to the last.
if attr[4] < 15: false else: true
var sixAttr: array[6, int]
while true:
var sumAttr = 0
for i in 0 .. 5:
sixAttr[i] = sumRolls(diceFourRolls())
sumAttr += sixAttr[i]
echo "The roll sums are, in order: ", sixAttr, ", which adds to ", sumAttr
if not twoFifteens(sixAttr) or sumAttr < 75: echo "Not good enough. Rerolling..."
else: break
</syntaxhighlight>
Sample output: <pre>
The roll sums are, in order: [8, 10, 16, 17, 10, 11], which adds to 72
Not good enough. Rerolling
The roll sums are, in order: [13, 13, 14, 13, 10, 16], which adds to 79
Not good enough. Rerolling
The roll sums are, in order: [12, 18, 16, 13, 17, 8], which adds to 84</pre>
=={{header|OCaml}}==
Original version by [http://rosettacode.org/wiki/User:Vanyamil User:Vanyamil]
<syntaxhighlight lang="ocaml">
(* Task : RPG_attributes_generator *)
(*
A programmatic solution to generating character attributes for an RPG
*)
(* Generates random whole values between 1 and 6. *)
let rand_die () : int = Random.int 6
(* Generates 4 random values and saves the sum of the 3 largest *)
let rand_attr () : int =
let four_rolls = [rand_die (); rand_die (); rand_die (); rand_die ()]
|> List.sort compare in
let three_best = List.tl four_rolls in
List.fold_left (+) 0 three_best
(* Generates a total of 6 values this way. *)
let rand_set () : int list=
[rand_attr (); rand_attr (); rand_attr ();
rand_attr (); rand_attr (); rand_attr ()]
(* Verifies conditions: total >= 75, at least 2 >= 15 *)
let rec valid_set () : int list=
let s = rand_set () in
let above_15 = List.fold_left (fun acc el -> if el >= 15 then acc + 1 else acc) 0 s in
let total = List.fold_left (+) 0 s in
if above_15 >= 2 && total >= 75
then s
else valid_set ()
(*** Output ***)
let _ =
let s = valid_set () in
List.iter (fun i -> print_int i; print_string ", ") s
</syntaxhighlight>
{{out}}
<pre>
11, 15, 11, 15, 14, 14,
</pre>
=={{header|Pascal|FreePascal}}==
<syntaxhighlight lang="pascal">
program attributes;
Line 1,661 ⟶ 2,944:
writeln(' ---');
end.
</syntaxhighlight>
{{out}}
<pre>
Line 1,696 ⟶ 2,979:
=={{header|Perl}}==
<
use List::Util 'sum';
Line 1,715 ⟶ 2,998:
printf "%s = %2d\n", $attr_names[$_], $attr[$_] for 0..$#attr;
printf "Sum = %d, with %d attributes >= $hero_attr_min\n", sum(@attr), heroic(@attr);</
{{out}}
<pre>Str = 13
Line 1,726 ⟶ 3,009:
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">numbers</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span>
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">numbers</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">ni</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_rand</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">numbers</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ni</span><span style="color: #0000FF;">)-</span><span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ni</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #000000;">numbers</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_ge</span><span style="color: #0000FF;">(</span><span style="color: #000000;">numbers</span><span style="color: #0000FF;">,</span><span style="color: #000000;">15</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">75</span> <span style="color: #008080;">and</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">2</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"re-rolling..."</span> <span style="color: #000080;font-style:italic;">-- (occasionally >20)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The 6 attributes generated are:\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"strength %d, dexterity %d, constitution %d, "</span><span style="color: #0000FF;">&</span>
<span style="color: #008000;">"intelligence %d, wisdom %d, and charisma %d.\n"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">numbers</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nTheir sum is %d and %d of them are >=15\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,752 ⟶ 3,038:
Their sum is 86 and 3 of them are >=15
</pre>
=={{header|Phixmonti}}==
{{trans|BASIC256}}
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: https://rosettacode.org/wiki/RPG_attributes_generator
by Galileo, 11/2022 #/
include ..\Utilitys.pmt
def d6 rand 6 * int 1 + enddef
( "STR" "CON" "DEX" "INT" "WIS" "CHA" )
true while
0 0
6 for drop 0 >ps
( d6 d6 d6 d6 ) len for get ps> + >ps endfor
min ps> swap -
dup >ps +
tps 15 > if swap 1 + swap endif
endfor
75 >= swap 2 >= and not
endwhile
0 swap
6 for
get print ": " print swap tps + swap ps> ?
endfor
drop "-------" ? "TOT: " print ?</syntaxhighlight>
{{out}}
<pre>STR: 14
CON: 9
DEX: 17
INT: 16
WIS: 13
CHA: 15
-------
TOT: 84
=== Press any key to exit ===</pre>
=={{header|PHP}}==
===Version 1===
<
$attributesTotal = 0;
Line 1,785 ⟶ 3,111:
}
print_r($attributes);</
===Version 2===
<
class CharacterGenerator {
Line 1,827 ⟶ 3,153:
print "Attribute Total: $attributesTotal\n";
print "Attributes: $attributesString";</
{{out}}
<pre>Attribute Total: 80
Attributes: 10, 12, 16, 17, 14, 11</pre>
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To add an attribute to some stats:
Allocate memory for an entry.
Put the attribute into the entry's attribute.
Append the entry to the stats.
An attribute is a number.
An entry is a thing with an attribute.
To find a count of attributes greater than fourteen in some stats:
Put 0 into the count.
Get an entry from the stats.
Loop.
If the entry is nil, exit.
If the entry's attribute is greater than 14, bump the count.
Put the entry's next into the entry.
Repeat.
To find a sum of some stats:
Put 0 into the sum.
Get an entry from the stats.
Loop.
If the entry is nil, exit.
Add the entry's attribute to the sum.
Put the entry's next into the entry.
Repeat.
To generate an attribute:
Put 0 into the attribute.
Put 6 into a minimum number.
Loop.
If a counter is past 4, break.
Pick a number between 1 and 6.
Add the number to the attribute.
If the number is less than the minimum, put the number into the minimum.
Repeat.
Subtract the minimum from the attribute.
To generate some stats (raw):
If a counter is past 6, exit.
Generate an attribute.
Add the attribute to the stats.
Repeat.
To generate some stats (valid):
Generate some raw stats (raw).
Find a sum of the raw stats.
If the sum is less than 75, destroy the raw stats; repeat.
Find a count of attributes greater than fourteen in the raw stats.
If the count is less than 2, destroy the raw stats; repeat.
Put the raw stats into the stats.
To run:
Start up.
Show some RPG attributes.
Wait for the escape key.
Shut down.
To show some RPG attributes:
Generate some stats (valid).
Find a sum of the stats.
Find a count of attributes greater than fourteen in the stats.
Write the stats on the console.
Destroy the stats.
Write "Total: " then the sum on the console.
Write "Number of stats greater than fourteen: " then the count on the console.
Some stats are some entries.
A sum is a number.
To write some stats on the console:
Get an entry from the stats.
Loop.
If the entry is nil, write "" on the console; exit.
Convert the entry's attribute to a string.
Write the string on the console without advancing.
If the entry's next is not nil, write ", " on the console without advancing.
Put the entry's next into the entry.
Repeat.</syntaxhighlight>
{{out}}
<pre>
13, 10, 17, 10, 18, 14
Total: 82
Number of stats greater than fourteen: 2
</pre>
=={{header|PureBasic}}==
<
#heroicAttributeCountMinimum = 2
#attributeSumMinimum = 75
Line 1,890 ⟶ 3,304:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre>Attributes generated: [13, 17, 17, 11, 9, 17]
Line 1,897 ⟶ 3,311:
=={{header|Python}}==
===Python: Simple===
<
random.seed()
attributes_total = 0
Line 1,923 ⟶ 3,337:
attributes_total = sum(attributes)
print(attributes_total, attributes)</
{{out}}
Line 1,930 ⟶ 3,344:
===Python: Nested Comprehensions #1===
<
random.seed()
total = 0
Line 1,944 ⟶ 3,358:
total = sum(attributes)
print(total, attributes)</
{{out}}
Line 1,952 ⟶ 3,366:
===Python: Nested Comprehensions #2===
With comprehensions for checking candidate values in the while expression.
<
def compute():
Line 1,963 ⟶ 3,377:
for i in range(3):
print(*compute())
</syntaxhighlight>
{{out}}
Line 1,973 ⟶ 3,387:
Composing a hero-generator from reusable functions:
{{Works with|Python|3.7}}
<
from itertools import islice
from random import randint
from operator import eq
Line 1,983 ⟶ 3,397:
def heroes(p):
'''Non-finite list of heroes matching
the requirements of predicate p.
'''
while True:
yield
until(p)(character)([])
)
Line 2,000 ⟶ 3,408:
def character(_):
'''A random character with six
integral attributes.
'''
return [
sum(sorted(map(
Line 2,010 ⟶ 3,419:
#
# main :: IO ()
def main():
Line 2,018 ⟶ 3,427:
def seventyFivePlusIncTwo15s(xs):
'''Sums to 75 or more,
and includes at least two 15s.
'''
return 75 <= sum(xs) and (
1 < len(list(filter(curry(eq)(15), xs)))
Line 2,032 ⟶ 3,442:
#
# curry :: ((a, b) -> c) -> a -> b -> c
def curry(f):
'''A curried function derived
from an uncurried function.
'''
return lambda x: lambda y: f(x, y)
# enumFromTo ::
def enumFromTo(m):
'''
return lambda n:
# randomRInt :: Int -> Int -> IO () -> Int
def randomRInt(m):
'''The return value of randomRInt is itself
called, yields a a new pseudo-random integer
in the range [m
'''
return lambda n: lambda _: randint(m, n)
Line 2,060 ⟶ 3,472:
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
return lambda xs: (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
Line 2,070 ⟶ 3,483:
# unlines :: [String] -> String
def unlines(xs):
'''A single string
of a list of strings with the newline character.
'''
return '\n'.join(xs)
Line 2,078 ⟶ 3,492:
def until(p):
'''The result of repeatedly applying f until p holds.
The initial seed value is x.
'''
def go(f, x):
v = x
Line 2,088 ⟶ 3,503:
if __name__ == '__main__':
main()</
<pre>A sample of 10:
Line 2,101 ⟶ 3,516:
79 -> (17, 15, 10, 11, 15, 11)
75 -> (15, 13, 7, 11, 14, 15)</pre>
===Python: One-liner===
Just because you can, doesn't mean you should.
<syntaxhighlight lang="python">
import random; print((lambda attr: f"Attributes: {attr}\nTotal: {sum(attr)}")((lambda func, roll_func: func(func, roll_func, roll_func()))((lambda func, roll_func, rolls: rolls if sum(rolls) >= 75 and rolls.count(15) >= 2 else func(func, roll_func, roll_func())), lambda: [sum(sorted(random.randint(1, 6) for _ in range(4))[1:]) for _ in range(6)])))
</syntaxhighlight>
<pre>
Attributes: [16, 15, 15, 14, 8, 10]
Total: 78
</pre>
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">[ 0 swap witheach + ] is sum ( [ --> n )
[ 0 ]'[ rot witheach
[ over do swap dip + ] drop ] is count ( [ --> n )
[ [] 4 times
[ 6 random 1+ join ]
sort behead drop sum ] is attribute ( --> n )
[ [] 6 times
[ attribute join ] ] is raw ( --> [ )
[ dup sum 74 > not iff
[ drop false ] done
count [ 14 > ] 1 > ] is valid ( [ --> b )
[ raw dup valid if
done
drop again ] is stats ( --> [ )
randomise
stats dup echo cr cr
say 'Sum: ' dup sum echo cr
say '# of attributes > 14: '
count [ 14 > ] echo</syntaxhighlight>
{{out}}
<pre>
[ 10 16 16 8 12 15 ]
Sum: 77
# of attributes > 14: 3
</pre>
=={{header|Racket}}==
<
(define (d6 . _)
Line 2,120 ⟶ 3,579:
(module+ main
(define-values (rolled-stats total) (generate-character))
(printf "Rolls:\t~a~%Total:\t~a" rolled-stats total))</
{{out}}
<pre>Rolls: (11 16 10 13 12 15)
Total: 77</pre>
=={{header|R}}==
The base library already has an attributes function, so we avoid using that name. Otherwise, this is R's bread and butter.
<syntaxhighlight lang="rsplus">genStats <- function()
{
stats <- c(STR = 0, DEX = 0, CON = 0, INT = 0, WIS = 0, CHA = 0)
for(i in seq_along(stats))
{
results <- sample(6, 4, replace = TRUE)
stats[i] <- sum(results[-which.min(results)])
}
if(sum(stats >= 15) < 2 || (stats["TOT"] <- sum(stats)) < 75) Recall() else stats
}
print(genStats())</syntaxhighlight>
{{out}}
<pre>STR DEX CON INT WIS CHA TOT
15 18 18 11 15 15 92 </pre>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo Star|2018.04.1}}
<syntaxhighlight lang="raku"
my @attr-names = <Str Int Wis Dex Con Cha>;
Line 2,142 ⟶ 3,619:
say @attr-names Z=> @attr;
say "Sum: {@attr.sum}, with {heroic(@attr)} attributes >= $hero_attr_min";</
{{out}}
<pre>
(Str => 15 Int => 16 Wis => 13 Dex => 11 Con => 15 Cha => 6)
Sum: 76, with 3 attributes >= 15
</pre>
=={{header|Red}}==
<syntaxhighlight lang="rebol">Red ["RPG attributes generator"]
raw-attribute: does [
sum next sort collect [
loop 4 [keep random/only 6]
]
]
raw-attributes: does [
collect [
loop 6 [keep raw-attribute]
]
]
valid-attributes?: func [b][
n: 0
foreach attr b [
if attr > 14 [n: n + 1]
]
all [
n > 1
greater? sum b 74
]
]
attributes: does [
until [
valid-attributes? a: raw-attributes
]
a
]
show-attributes: function [a][
i: 1
foreach stat-name [
"Strength"
"Dexterity"
"Constitution"
"Intelligence"
"Wisdom"
"Charisma"
][
print [rejoin [stat-name ":"] a/:i]
i: i + 1
]
print "-----------------"
print ["Sum:" sum a]
print [n "attributes > 14"]
]
show-attributes attributes</syntaxhighlight>
{{out}}
<pre>
Strength: 14
Dexterity: 11
Constitution: 16
Intelligence: 9
Wisdom: 16
Charisma: 16
-----------------
Sum: 82
3 attributes > 14
</pre>
=={{header|REXX}}==
===version 1===
<
Generates 4 random, whole values between 1 and 6.
Saves the sum of the 3 largest values.
Line 2,214 ⟶ 3,756:
swl=swl wa.i
End
Return strip(swl)</
{{out}}
<pre>I:\>rexx cast
Line 2,225 ⟶ 3,767:
===version 2===
This REXX version doesn't need a sort to compute the sum of the largest three (of four) values.
<
do until m>=2 & $$>=75; $$= 0; list= /*do rolls until requirements are met. */
m= 0 /*the number of values ≥ 15 (so far).*/
Line 2,238 ⟶ 3,780:
end /*do 6*/ /* [↑] gen six core attribute values. */
end /*until*/ /*stick a fork in it, we're all done. */
say 'The total for ' list " is ──► " $$', ' m " entries are ≥ 15."</
{{out|output|text= when using the default (internal) inputs:}}
<pre>
Line 2,246 ⟶ 3,788:
===version 3===
A variation of version 2
<
Do n=1 By 1 until m>=2 & tot>=75;
slist=''
Line 2,265 ⟶ 3,807:
Say 'the total for' space(slist) 'is -->' tot', 'm' entries are >= 15.'
end
Say 'Solution found with' n 'iterations'</
{{out}}
<pre>I:\>rexx rpg
Line 2,274 ⟶ 3,816:
=={{header|Ring}}==
<
# Project : RPG Attributes Generator
Line 2,319 ⟶ 3,861:
line = line + "])"
see line + nl
</syntaxhighlight>
Output:
<pre>
Line 2,326 ⟶ 3,868:
=={{header|Ruby}}==
<
until res.sum >= 75 && res.count{|n| n >= 15} >= 2 do
res = Array.new(6) do
Line 2,336 ⟶ 3,878:
p res
puts "sum: #{res.sum}"
</syntaxhighlight>
{{out}}
<pre>[12, 14, 17, 12, 16, 9]
sum: 80
</pre>
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">dim statnames$(6)
data "STR", "CON", "DEX", "INT", "WIS", "CHA"
for i = 1 to 6
read statnames$(i)
next i
dim stat(6)
acceptable = false
while 1
sum = 0 : n15 = 0
for i = 1 to 6
stat(i) = rollstat()
sum = sum + stat(i)
if stat(i) >= 15 then n15 = n15 + 1
next i
if sum >= 75 and n15 >= 2 then exit while
wend
for i = 1 to 6
print statnames$(i); ": "; stat(i)
next i
print "-------"
print "TOT: "; sum
end
function d6()
d6 = 1 + int(rnd(1) * 6)
end function
function rollstat()
a = d6() : b = d6() : c = d6() : d = d6()
rollstat = a + b + c + d - min(min(a, b), min(c, d))
end function</syntaxhighlight>
=={{header|Rust}}==
Line 2,346 ⟶ 3,923:
{{libheader|rand}}
{{works with|Rust|2018}}
<
use rand::distributions::Uniform;
use rand::prelude::{thread_rng, ThreadRng};
Line 2,423 ⟶ 4,000:
}
}
</syntaxhighlight>
{{out}}
Sample output, running the generator ten times:
Line 2,441 ⟶ 4,018:
=={{header|Scala}}==
<
import scala.util.Random
Random.setSeed(1)
Line 2,462 ⟶ 4,039:
println("picked => " + getCharacter.mkString("[", ",", "]"))
</syntaxhighlight>
<pre>
Line 2,473 ⟶ 4,050:
=={{header|Seed7}}==
<
const proc: main is func
Line 2,510 ⟶ 4,087:
writeln(" ----");
writeln("Total " <& total lpad 3);
end func;</
{{out}}
Line 2,524 ⟶ 4,101:
Total 76
</pre>
=={{header|True BASIC}}==
{{trans|FreeBASIC}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">FUNCTION min(a, b)
IF a < b THEN LET min = a ELSE LET min = b
END FUNCTION
FUNCTION d6
LET d6 = 1 + INT(RND * 6)
END FUNCTION
FUNCTION rollstat
LET a = d6
LET b = d6
LET c = d6
LET d = d6
LET rollstat = a + b + c + d - min(min(a, b), min(c, d))
END FUNCTION
DIM statnames$(6)
DATA "STR", "CON", "DEX", "INT", "WIS", "CHA"
FOR i = 1 TO 6
READ statnames$(i)
NEXT i
DIM stat(6)
LET acceptable = 0
RANDOMIZE ! RANDOMIZE TIMER en QBasic
DO
LET sum = 0
LET n15 = 0
FOR i = 1 to 6
LET stat(i) = rollstat
LET sum = sum + stat(i)
IF stat(i) >= 15 THEN LET n15 = n15 + 1
NEXT i
IF sum >= 75 AND n15 >= 2 THEN LET acceptable = 1
LOOP UNTIL acceptable = 1
FOR i = 1 to 6
PRINT statnames$(i); ": "; stat(i)
NEXT i
PRINT "--------"
PRINT "TOT: "; sum
END</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
=={{header|uBasic/4tH}}==
{{trans|Yabasic}}
<syntaxhighlight lang="text">dim @n(6)
@n(0) := "STR"
@n(1) := "CON"
@n(2) := "DEX"
@n(3) := "INT"
@n(4) := "WIS"
@n(5) := "CHA"
dim @s(6)
do
s = 0 : n = 0
for i = 0 to 5
@s(i) = FUNC(_rollstat)
s = s + @s(i)
if @s(i) > 14 then n = n + 1
next
until (s > 74) * (n > 1)
loop
for i = 0 to 5
print show(@n(i)); ":"; using "__", @s(i)
next
print "----" : Print "TOT: "; using "__", s
end
' simulates a marked regular hexahedron coming to rest on a plane
_d6 return (1 + rnd(6))
' rolls four dice, returns the sum of the three highest
_rollstat
local (4)
a@ = FUNC(_d6) : b@ = FUNC(_d6) : c@ = FUNC(_d6) : d@ = FUNC(_d6)
return (a@ + b@ + c@ + d@ - Min(Min(a@, b@), Min(c@, d@)))</syntaxhighlight>
{{Out}}
<pre>STR: 17
CON: 15
DEX: 8
INT: 12
WIS: 14
CHA: 16
----
TOT: 82
0 OK, 0:384</pre>
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{works with|Zsh}}
<syntaxhighlight lang="sh">function main {
typeset attrs=(str dex con int wis cha)
typeset -A values
typeset attr
typeset -i value total fifteens
while true; do
fifteens=0
total=0
for attr in "${attrs[@]}"; do
# "random" values repeat in zsh if run in a subshell
r4d6drop >/tmp/$$
read value </tmp/$$
values[$attr]=$value
(( total += value ))
if (( value >= 15 )); then
(( fifteens += 1 ))
fi
done
if (( total >= 75 && fifteens >= 2 )); then
break
fi
done
rm -f /tmp/$$
for attr in "${attrs[@]}"; do
printf '%s: %d\n' "$attr" "${values[$attr]}"
done
}
function r4d6drop {
typeset -i d1=RANDOM%6+1 d2=RANDOM%6+1 d3=RANDOM%6+1 d4=RANDOM%6+1
typeset e=$(printf '%s\n' $d1 $d2 $d3 $d4 |
sort -n | tail -n +2 | tr $'\n' +)
printf '%d\n' $(( ${e%+} ))
}
main "$@"
</syntaxhighlight>
{{Out}}
<pre>str: 12
dex: 15
con: 15
int: 14
wis: 8
cha: 12</pre>
=={{header|Visual Basic .NET}}==
repeats until a successful outcome occurs
<
Dim r As New Random
Line 2,552 ⟶ 4,274:
Loop Until good
End Sub
End Module</
{{out}}
sample outputs:
Line 2,566 ⟶ 4,288:
attribs: 17, 16, 14, 8, 8, 9, sum=72, (low sum, high vals=2) - failure
attribs: 18, 16, 13, 9, 9, 10, sum=75, (good sum, high vals=2) - success</pre>
=={{header|Wren}}==
{{libheader|Wren-sort}}
<syntaxhighlight lang="wren">import "random" for Random
import "./sort" for Sort
var rand = Random.new()
var vals = List.filled(6, 0)
while (true) {
for (i in 0..5) {
var rns = List.filled(4, 0)
for (j in 0..3) rns[j] = rand.int(1, 7)
var sum = rns.reduce { |acc, n| acc + n }
Sort.insertion(rns)
vals[i] = sum - rns[0]
}
var total = vals.reduce { |acc, n| acc + n }
if (total >= 75) {
var fifteens = vals.count { |n| n >= 15 }
if (fifteens >= 2) {
System.print("The six values are: %(vals)")
System.print("Their total is: %(total)")
break
}
}
}</syntaxhighlight>
{{out}}
Sample run:
<pre>
The six values are: [15, 16, 10, 12, 13, 13]
Their total is: 79
</pre>
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func Gen; \Return sum of the three largest of four random values
int I, R, Min, SI, Sum, Die(4);
[Min:= 7; Sum:= 0;
for I:= 0 to 4-1 do
[R:= Ran(6)+1; \R = 1..6
if R < Min then
[Min:= R; SI:= I];
Sum:= Sum+R;
Die(I):= R;
];
return Sum - Die(SI);
];
int Total, Count, J, Value(6);
[repeat Total:= 0; Count:= 0;
for J:= 0 to 6-1 do
[Value(J):= Gen;
if Value(J) >= 15 then Count:= Count+1;
Total:= Total + Value(J);
];
until Total >= 75 and Count >= 2;
Text(0, "Total: "); IntOut(0, Total); CrLf(0);
for J:= 0 to 6-1 do
[IntOut(0, Value(J)); ChOut(0, ^ )];
CrLf(0);
]</syntaxhighlight>
{{out}}
<pre>
Total: 79
13 17 11 10 16 12
</pre>
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="freebasic">sub d6()
//simulates a marked regular hexahedron coming to rest on a plane
return 1 + int(ran(6))
end sub
sub roll_stat()
//rolls four dice, returns the sum of the three highest
a = d6() : b = d6(): c = d6(): d = d6()
return a + b + c + d - min(min(a, b), min(c, d))
end sub
dim statnames$(6)
statnames$(1) = "STR"
statnames$(2) = "CON"
statnames$(3) = "DEX"
statnames$(4) = "INT"
statnames$(5) = "WIS"
statnames$(6) = "CHA"
dim stat(6)
acceptable = false
repeat
sum = 0
n15 = 0
for i = 1 to 6
stat(i) = roll_stat()
sum = sum + stat(i)
if stat(i) >= 15 then n15 = n15 + 1 : fi
next i
if sum >= 75 and n15 >= 2 then acceptable = true : fi
until acceptable
for i = 1 to 6
print statnames$(i), ": ", stat(i) using "##"
next i
print "-------\nTOT: ", sum
end</syntaxhighlight>
{{out}}
<pre>Igual que la entrada de FreeBASIC.</pre>
=={{header|Zig}}==
<syntaxhighlight lang="zig">const std = @import("std");
const dice = 6;
const rolls = 4;
const stat_count = 6;
// requirements
const min_stat_sum = 75;
const min_high_stat_count = 2;
const high_stat_threshold = 15;
const RollResult = struct { stats: [stat_count]u16, total: u16 };
fn roll_attribute(rand: std.rand.Random) u16 {
var min_roll: u16 = dice;
var total: u16 = 0;
for (0..rolls) |_| {
const roll = rand.uintAtMost(u16, dice - 1) + 1;
if (min_roll > roll) {
min_roll = roll;
}
total += roll;
}
return total - min_roll;
}
fn roll_stats(rand: std.rand.Random) RollResult {
var result: RollResult = RollResult{
.stats = undefined,
.total = 0,
};
var high_stat_count: u16 = 0;
var i: u16 = 0;
while (i < stat_count) {
// roll a stat
result.stats[i] = roll_attribute(rand);
result.total += result.stats[i];
if (result.stats[i] >= high_stat_threshold) high_stat_count += 1;
// find the maximum possible total
const stats_remain = stat_count - i - 1;
const max_possible_total = result.total + dice * (rolls - 1) * stats_remain;
// if it is below the minimum or there are not enough stats over 15 reset
if (max_possible_total < min_stat_sum or high_stat_count + stats_remain < 2) {
i = 0;
result.total = 0;
high_stat_count = 0;
} else {
i += 1;
}
}
return result;
}
pub fn main() !void {
// Create random generator
var prng = std.rand.DefaultPrng.init(blk: {
var seed: u64 = undefined;
try std.os.getrandom(std.mem.asBytes(&seed));
break :blk seed;
});
const rand = prng.random();
const stats = roll_stats(rand);
const stdout = std.io.getStdOut().writer();
try stdout.print("Total: {}\n", .{stats.total});
try stdout.print("Stats: [ ", .{});
for (stats.stats) |stat| {
try stdout.print("{} ", .{stat});
}
try stdout.print("]\n", .{});
}
</syntaxhighlight>
{{out}}
<pre>Total: 79
Stats: [ 14 13 5 16 15 16 ]</pre>
=={{header|zkl}}==
<
do{
attrs.clear();
Line 2,577 ⟶ 4,494:
}while((S=attrs.sum(0))<75 or (N=attrs.filter('>=(15)).len())<2);
println("Random numbers: %s\nSums to %d, with %d >= 15"
.fmt(attrs.concat(","),S,N));</
{{out}}
<pre>
|