RPG attributes generator: Difference between revisions

Added Easylang
(Added Easylang)
 
(43 intermediate revisions by 24 users not shown)
Line 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}}==
 
<langsyntaxhighlight lang="asm"> bits 16
cpu 8086
putch: equ 2h
Line 123 ⟶ 147:
section .bss
rnddat: resb 4 ; RNG state
attrs: resb 6 ; Rolled attributes</langsyntaxhighlight>
 
{{out}}
Line 138 ⟶ 162:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program rpg64.s */
Line 374 ⟶ 398:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 386 ⟶ 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 391 ⟶ 549:
{{works with|Dyalog APL}}
 
<langsyntaxhighlight APLlang="apl">roll←{(+/-⌊/)¨?¨56/⊂4/6}⍣{(75≤+/⍺)∧2≤+/⍺≥15}</langsyntaxhighlight>
 
{{out}}
 
<pre> roll''
1510 159 1713 1516 1811 17
roll''
18 15 15 13 16
roll''
18 14 1712 15 168 15 14
roll''
1816 1316 1715 17 1416 11
roll''
1315 1814 168 1615 1412 15</pre>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 732 ⟶ 888:
bx lr
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">vals: []
 
while [or? 75 > sum vals
Line 750 ⟶ 906:
 
print ["values:" vals ]
print ["with sum:" sum vals]</langsyntaxhighlight>
 
=={{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}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <time.h>
Line 795 ⟶ 1,061:
}
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 808 ⟶ 1,074:
=={{header|C sharp|C#}}==
{{trans|Visual Basic .NET}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 839 ⟶ 1,105:
} while (!good);
}
}</langsyntaxhighlight>
{{out}}
sample outputs:
Line 848 ⟶ 1,114:
=={{header|C++}}==
GCC 4.9.2, unoptimised.
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <ctime>
#include <iostream>
Line 899 ⟶ 1,165:
return 0;
}</langsyntaxhighlight>
{{out}}
Sample run:
Line 908 ⟶ 1,174:
 
=={{header|Caché ObjectScript}}==
<syntaxhighlight lang="caché objectscript">RPGGEN
<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 953 ⟶ 1,219:
} while (result '= 3)
quit</langsyntaxhighlight>
{{out}}<pre>
Line 967 ⟶ 1,233:
</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
<lang gwbasic>
110 rem rosetta code - commodore basic
10 rem rpg character roller
120 dim di(3):rem dice
20 rem rosetta code - commodore basic
100130 dim diat(45),at$(5):rem diceattributes as follows:
140 at$(0)="Strength"
105 dim at(6),at$(6):rem attributes as follows:
110150 at$(1)="StrengthDexterity"
115160 at$(2)="DexterityConstitution"
120170 at$(3)="ConstitutionIntelligence"
125180 at$(4)="IntelligenceWisdom"
130190 at$(5)="WisdomCharisma"
200 pt=0:sa=0:rem points total and number of strong attributes (15+)
135 at$(6)="Charisma"
210 print chr$(147);chr$(14);chr$(29);chr$(17);"Rolling..."
140 pt=0:sa=0:rem points total and number of strong attributes (15+)
220 for ai=0 to 5:rem attribute index
145 print chr$(147);chr$(14);"{right}{down}Rolling..."
150230 for aii=10 to 3:di(i)=int(rnd(.)*6)+1:rem attributenext indexi
240 gosub 450
155 for i=1 to 4:di(i)=int(rnd(1)*6)+1:next i
250 dt=0:rem dice total
160 gosub 2000
260 for i=0 to 2:dt=dt+di(i):next i:rem take top 3
165 ds=0:rem dice sum
270 at(ai)=dt:pt=pt+dt
170 for i=1 to 3:ds=ds+di(i):next i:rem take top 3
280 if dt>=15 then sa=sa+1
175 at(ai)=ds:pt=pt+ds
290 next ai
180 if ds>=15 then sa=sa+1
300 if pt<75 or sa<2 then goto 200
185 next ai
310 print chr$(147);"Character Attributes:"
190 if pt<75 or sa<2 then goto 140
320 print
195 print chr$(147);"Character Attributes:"
330 for ai=0 to 5
200 print
340 print spc(13-len(at$(ai)));at$(ai);":";tab(14);at(ai)
205 for ai=1 to 6
350 next ai
210 print spc(13-len(at$(ai)));at$(ai);":";tab(14);at(ai)
360 print
215 next ai
370 print " Total:";tab(14);pt
220 print
380 print
225 print " Total:";tab(14);pt
230390 print "Do you accept? ";
400 get k$:if k$<>"y" and k$<>"n" then 400
235 print "Do you accept? ";
410 print k$
240 get k$:if k$<>"y" and k$<>"n" then 240
420 if k$="n" then goto 200
245 print k$
430 print:print "Excellent. Good luck on your adventure!"
250 if k$="n" then goto 140
440 end
255 print:print "Excellent. Good luck on your adventure!"
450 rem "sort" dice - really just put smallest one last
260 end
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
2000 rem sort dice
480 next x
2005 for x=1 to 3:for y=i+1 to 4
490 return</syntaxhighlight>
2010 if di(x)<di(y) then di(0)=di(x):di(x)=di(y):di(y)=di(0)
2015 next j,i
2020 return
</lang>
 
{{out}}
Line 1,057 ⟶ 1,403:
 
=={{header|Common Lisp}}==
===Mapping functions===
<lang lisp>
<syntaxhighlight lang="lisp">
(defpackage :rpg-generator
(:use :cl)
Line 1,076 ⟶ 1,423:
(format t ">= 15: ~A~%" (count-if (lambda (n) (>= n 15)) scores))
(return scores)))
</syntaxhighlight>
</lang>
=== 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}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
include "argv.coh";
 
Line 1,175 ⟶ 1,566:
print("\nTotal: ");
print_i8(total);
print_nl();</langsyntaxhighlight>
 
{{out}}
Line 1,190 ⟶ 1,581:
 
=={{header|Crystal}}==
<langsyntaxhighlight Rubylang="ruby">def roll_stat
dices = Array(Int32).new(4) { rand(1..6) }
dices.sum - dices.min
Line 1,205 ⟶ 1,596:
stats = roll_character
puts "stats: #{stats}, sum is #{stats.sum}"
end</langsyntaxhighlight>
 
sample output:
Line 1,223 ⟶ 1,614:
{{libheader| System.Generics.Collections}}
{{Trans|C#}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program RPG_Attributes_Generator;
 
Line 1,337 ⟶ 1,728:
end.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,346 ⟶ 1,737:
=={{header|Dyalect}}==
{{trans|C#}}
<langsyntaxhighlight lang="dyalect">func getThree(n) {
var g3 = []
for i in 0..33 {
g3.addAdd(rnd(max: n) + 1)
}
g3.sortSort()
g3.removeAtRemoveAt(0)
g3
}
Line 1,359 ⟶ 1,750:
var g6 = []
for i in 0..5 {
g6.addAdd(getThree(6).sumSum())
}
g6
}
func Array.sumSum() {
var acc = 0
for x in this {
Line 1,372 ⟶ 1,763:
}
func Array.findAllFindAll(pred) {
for x in this when pred(x) {
yield x
Line 1,382 ⟶ 1,773:
while !good {
var gs = getSix()
var gss = gs.sumSum()
var hvc = gs.findAllFindAll(x => x > 14).lenLength()
print("attribs: \(gs), sum=\(gss), ", terminator: "")
let gl = gss >= 75 ? "good" : "low"
print("(\(gl) sum, high vals=\(hvc))", terminator: "")
good = gs.sumSum() >= 75 && hvc > 1
print(" - " + (good ? "success" : "failure"))
}</langsyntaxhighlight>
 
{{out}}
Line 1,396 ⟶ 1,787:
 
=={{header|EasyLang}}==
{{trans|BASIC256}}
 
<syntaxhighlight>
<lang>len v[] 6
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
vsum sum = 0
vmin n15 = 0
for i rangeto 6
val stat[i] = 0rollstat
min sum += 6stat[i]
for j rangeif 4stat[i] >= 15
h = random 6n15 += 1
val += h
if h < min
min = h
.
.
until valsum ->= min75 and n15 >= 2
v[i] = val
if val >= 15
vmin += 1
.
vsum += val
.
until vsum >= 75 and vmin >= 2
.
for i to 6
print "Attributes: " & " " & v[]
print "Total: " print state$[i] & ": " & vsum</lang>stat[i]
.
print "-------"
print "TOT: " & sum
</syntaxhighlight>
 
{{out}}
<pre>
STR: 13
Attributes: [ 18 13 17 15 9 11 ]
CON: 11
Total: 83
DEX: 16
INT: 8
WIS: 17
CHA: 18
-------
TOT: 83
</pre>
 
=={{header|Factor}}==
{{Works with|Factor|0.98}}
<langsyntaxhighlight lang="factor">USING: combinators.short-circuit dice formatting io kernel math
math.statistics qw sequences ;
IN: rosetta-code.rpg-attributes-generator
Line 1,455 ⟶ 1,857:
[ "%s: %d\n" printf ] 2each nl stats-info ;
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 1,470 ⟶ 1,872:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">#define min(a, b) iif(a < b, a, b)
 
function d6() as integer
Line 1,503 ⟶ 1,905:
next i
print "--------"
print using "TOT: ##";sum</langsyntaxhighlight>
{{out}}<pre>STR: 14
CON: 11
Line 1,515 ⟶ 1,917:
 
=={{header|FOCAL}}==
<langsyntaxhighlight FOCALlang="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
Line 1,538 ⟶ 1,940:
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)</langsyntaxhighlight>
 
{{out}}
Line 1,560 ⟶ 1,962:
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}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,607 ⟶ 2,118:
break
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,619 ⟶ 2,130:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Monad (replicateM)
import System.Random (randomRIO)
import Data.Bool (bool)
Line 1,637 ⟶ 2,148:
-------------------------- TEST ---------------------------
main :: IO ()
main = replicateM 10 character >>= mapM_ (print . (sum >>= (,)))</langsyntaxhighlight>
{{Out}}
<pre>Sample computation:
Line 1,654 ⟶ 2,165:
=={{header|J}}==
'twould be more efficient to work with index origin 0, then increment the roll once at output.
<syntaxhighlight lang="j">
<lang J>
roll=: [:1 >:+ 4 6 ?@:$ 6:
massage=: +/ - <./
generate_attributes=: massage@:roll
Line 1,667 ⟶ 2,178:
NB. use: generate_character 'name'
generate_character=: (; (+/ ; ])@:([: generate_attributes@:show Until accept 0:))&>@:boxopen
</syntaxhighlight>
</lang>
 
 
Line 1,700 ⟶ 2,211:
 
=={{header|Java}}==
<langsyntaxhighlight Javalang="java">import java.util.List;
import java.util.Random;
import java.util.stream.Stream;
Line 1,733 ⟶ 2,244:
}
}
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,742 ⟶ 2,253:
=={{header|Javascript}}==
===Imperative===
<langsyntaxhighlight lang="javascript">function roll() {
const stats = {
total: 0,
Line 1,775 ⟶ 2,286:
${rolledCharacter.rolls.join(', ')}
 
Their sum is ${rolledCharacter.total} and ${rolledCharacter.rolls.filter(a => a >= 15).length} of them are >= 15`);</langsyntaxhighlight>
 
{{out}}
Line 1,788 ⟶ 2,299:
===Functional===
{{Trans|Python}} (Functional composition version)
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,911 ⟶ 2,422:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
A sample of 10 character attribute sets:
Line 1,924 ⟶ 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}}==
<langsyntaxhighlight lang="julia">roll_skip_lowest(dice, sides) = (r = rand(collect(1:sides), dice); sum(r) - minimum(r))
 
function rollRPGtoon()
Line 1,947 ⟶ 2,551:
rollRPGtoon()
rollRPGtoon()
</langsyntaxhighlight>{{output}}<pre>
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,954 ⟶ 2,558:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="kotlin">import kotlin.random.Random
 
fun main() {
Line 1,969 ⟶ 2,573:
break
}
}</langsyntaxhighlight>
 
{{output}}
Line 1,976 ⟶ 2,580:
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}}==
<langsyntaxhighlight Mathematicalang="mathematica">valid = False;
While[! valid,
try = Map[Total[TakeLargest[#, 3]] &,
Line 1,987 ⟶ 2,740:
]
]
{Total[try], try}</langsyntaxhighlight>
{{out}}
<pre>{78, {13, 15, 9, 13, 12, 16}}</pre>
Line 1,993 ⟶ 2,746:
=={{header|min}}==
{{works with|min|0.19.6}}
<langsyntaxhighlight lang="min">randomize ; Seed the rng with current timestamp.
 
; Implement some general operators we'll need that aren't in the library.
Line 2,009 ⟶ 2,762:
(big (dup special?) () (pop big) () linrec) :stats ; Roll a set of big and special attributes.
 
stats puts "Total: " print! sum puts!</langsyntaxhighlight>
{{out}}
<pre>
Line 2,017 ⟶ 2,770:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">roll = function()
results = []
for i in range(0,3)
Line 2,043 ⟶ 2,796:
end while
print "Success!"
</syntaxhighlight>
</lang>
{{out}}
<pre>Attribute values: 11, 13, 8, 10, 8, 10
Line 2,062 ⟶ 2,815:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">
<lang Nim>
# Import "random" to get random numbers and "algorithm" to get sorting functions for arrays.
import random, algorithm
Line 2,096 ⟶ 2,849:
if not twoFifteens(sixAttr) or sumAttr < 75: echo "Not good enough. Rerolling..."
else: break
</syntaxhighlight>
</lang>
 
Sample output: <pre>
Line 2,107 ⟶ 2,860:
=={{header|OCaml}}==
Original version by [http://rosettacode.org/wiki/User:Vanyamil User:Vanyamil]
<syntaxhighlight lang="ocaml">
<lang OCaml>
(* Task : RPG_attributes_generator *)
 
Line 2,143 ⟶ 2,896:
let s = valid_set () in
List.iter (fun i -> print_int i; print_string ", ") s
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,151 ⟶ 2,904:
=={{header|Pascal|FreePascal}}==
 
<syntaxhighlight lang="pascal">
<lang Pascal>
program attributes;
 
Line 2,191 ⟶ 2,944:
writeln(' ---');
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,226 ⟶ 2,979:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use List::Util 'sum';
 
Line 2,245 ⟶ 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);</langsyntaxhighlight>
{{out}}
<pre>Str = 13
Line 2,256 ⟶ 3,009:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence numbers = repeat(0,6)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer t,n
<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>
while true do
<span style="color: #004080;">integer</span> <span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span>
for i=1 to length(numbers) do
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
sequence ni = sq_rand(repeat(6,4))
<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>
numbers[i] = sum(ni)-min(ni)
<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>
end for
<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>
t = sum(numbers)
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
n = sum(sq_ge(numbers,15))
<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>
if t>=75 and n>=2 then exit end if
<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>
?"re-rolling..." -- (occasionally >20)
<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>
end while
<span style="color: #0000FF;">?</span><span style="color: #008000;">"re-rolling..."</span> <span style="color: #000080;font-style:italic;">-- (occasionally &gt;20)</span>
printf(1,"The 6 attributes generated are:\n")
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
printf(1,"strength %d, dexterity %d, constitution %d, "&
<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>
"intelligence %d, wisdom %d, and charisma %d.\n",
<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>
numbers)
<span style="color: #008000;">"intelligence %d, wisdom %d, and charisma %d.\n"</span><span style="color: #0000FF;">,</span>
printf(1,"\nTheir sum is %d and %d of them are >=15\n",{t,n})</lang>
<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 &gt;=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 2,282 ⟶ 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===
<langsyntaxhighlight lang="php"><?php
 
$attributesTotal = 0;
Line 2,315 ⟶ 3,111:
}
 
print_r($attributes);</langsyntaxhighlight>
 
===Version 2===
<langsyntaxhighlight lang="php"><?php
class CharacterGenerator {
Line 2,357 ⟶ 3,153:
print "Attribute Total: $attributesTotal\n";
print "Attributes: $attributesString";</langsyntaxhighlight>
 
{{out}}
Line 2,364 ⟶ 3,160:
 
=={{header|Plain English}}==
<langsyntaxhighlight lang="plainenglish">To add an attribute to some stats:
Allocate memory for an entry.
Put the attribute into the entry's attribute.
Line 2,443 ⟶ 3,239:
If the entry's next is not nil, write ", " on the console without advancing.
Put the entry's next into the entry.
Repeat.</langsyntaxhighlight>
{{out}}
<pre>
Line 2,452 ⟶ 3,248:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang="purebasic">#heroicAttributeMinimum = 15
#heroicAttributeCountMinimum = 2
#attributeSumMinimum = 75
Line 2,508 ⟶ 3,304:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Sample output:
<pre>Attributes generated: [13, 17, 17, 11, 9, 17]
Line 2,515 ⟶ 3,311:
=={{header|Python}}==
===Python: Simple===
<langsyntaxhighlight lang="python">import random
random.seed()
attributes_total = 0
Line 2,541 ⟶ 3,337:
attributes_total = sum(attributes)
print(attributes_total, attributes)</langsyntaxhighlight>
 
{{out}}
Line 2,548 ⟶ 3,344:
 
===Python: Nested Comprehensions #1===
<langsyntaxhighlight lang="python">import random
random.seed()
total = 0
Line 2,562 ⟶ 3,358:
total = sum(attributes)
print(total, attributes)</langsyntaxhighlight>
 
{{out}}
Line 2,570 ⟶ 3,366:
===Python: Nested Comprehensions #2===
With comprehensions for checking candidate values in the while expression.
<langsyntaxhighlight lang="python">import random
 
def compute():
Line 2,581 ⟶ 3,377:
for i in range(3):
print(*compute())
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,591 ⟶ 3,387:
Composing a hero-generator from reusable functions:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''RPG Attributes Generator'''
 
from itertools import islice
Line 2,707 ⟶ 3,503:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
<pre>A sample of 10:
 
Line 2,723 ⟶ 3,519:
===Python: One-liner===
Just because you can, doesn't mean you should.
<langsyntaxhighlight 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>
</lang>
<pre>
Attributes: [16, 15, 15, 14, 8, 10]
Line 2,732 ⟶ 3,528:
 
=={{header|Quackery}}==
<langsyntaxhighlight lang="quackery">[ 0 swap witheach + ] is sum ( [ --> n )
 
[ 0 ]'[ rot witheach
Line 2,756 ⟶ 3,552:
say 'Sum: ' dup sum echo cr
say '# of attributes > 14: '
count [ 14 > ] echo</langsyntaxhighlight>
{{out}}
<pre>
Line 2,766 ⟶ 3,562:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
 
(define (d6 . _)
Line 2,783 ⟶ 3,579:
(module+ main
(define-values (rolled-stats total) (generate-character))
(printf "Rolls:\t~a~%Total:\t~a" rolled-stats total))</langsyntaxhighlight>
 
{{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" perl6line>my ( $min_sum, $hero_attr_min, $hero_count_min ) = 75, 15, 2;
my @attr-names = <Str Int Wis Dex Con Cha>;
 
Line 2,805 ⟶ 3,619:
 
say @attr-names Z=> @attr;
say "Sum: {@attr.sum}, with {heroic(@attr)} attributes >= $hero_attr_min";</langsyntaxhighlight>
{{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===
<langsyntaxhighlight lang="rexx">/* REXX
Generates 4 random, whole values between 1 and 6.
Saves the sum of the 3 largest values.
Line 2,877 ⟶ 3,756:
swl=swl wa.i
End
Return strip(swl)</langsyntaxhighlight>
{{out}}
<pre>I:\>rexx cast
Line 2,888 ⟶ 3,767:
===version 2===
This REXX version doesn't need a sort to compute the sum of the largest three (of four) values.
<langsyntaxhighlight lang="rexx">/*REXX program generates values for six core attributes for a RPG (Role Playing Game).*/
do until m>=2 & $$>=75; $$= 0; list= /*do rolls until requirements are met. */
m= 0 /*the number of values ≥ 15 (so far).*/
Line 2,901 ⟶ 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."</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default (internal) inputs:}}
<pre>
Line 2,909 ⟶ 3,788:
===version 3===
A variation of version 2
<langsyntaxhighlight lang="rexx">/*REXX program generates values for six core attributes for an RPG (Role Playing Game).*/
Do n=1 By 1 until m>=2 & tot>=75;
slist=''
Line 2,928 ⟶ 3,807:
Say 'the total for' space(slist) 'is -->' tot', 'm' entries are >= 15.'
end
Say 'Solution found with' n 'iterations'</langsyntaxhighlight>
{{out}}
<pre>I:\>rexx rpg
Line 2,937 ⟶ 3,816:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : RPG Attributes Generator
 
Line 2,982 ⟶ 3,861:
line = line + "])"
see line + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,989 ⟶ 3,868:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">res = []
until res.sum >= 75 && res.count{|n| n >= 15} >= 2 do
res = Array.new(6) do
Line 2,999 ⟶ 3,878:
p res
puts "sum: #{res.sum}"
</syntaxhighlight>
</lang>
{{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 3,009 ⟶ 3,923:
{{libheader|rand}}
{{works with|Rust|2018}}
<langsyntaxhighlight lang="rust">
use rand::distributions::Uniform;
use rand::prelude::{thread_rng, ThreadRng};
Line 3,086 ⟶ 4,000:
}
}
</syntaxhighlight>
</lang>
{{out}}
Sample output, running the generator ten times:
Line 3,104 ⟶ 4,018:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">
import scala.util.Random
Random.setSeed(1)
Line 3,125 ⟶ 4,039:
 
println("picked => " + getCharacter.mkString("[", ",", "]"))
</syntaxhighlight>
</lang>
 
<pre>
Line 3,136 ⟶ 4,050:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: main is func
Line 3,173 ⟶ 4,087:
writeln(" ----");
writeln("Total " <& total lpad 3);
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,187 ⟶ 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
<langsyntaxhighlight lang="vbnet">Module Module1
 
Dim r As New Random
Line 3,215 ⟶ 4,274:
Loop Until good
End Sub
End Module</langsyntaxhighlight>
{{out}}
sample outputs:
Line 3,232 ⟶ 4,291:
=={{header|Wren}}==
{{libheader|Wren-sort}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
import "./sort" for Sort
 
var rand = Random.new()
Line 3,254 ⟶ 4,313:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,262 ⟶ 4,321:
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}}==
<langsyntaxhighlight lang="zkl">reg attrs=List(), S,N;
do{
attrs.clear();
Line 3,273 ⟶ 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));</langsyntaxhighlight>
{{out}}
<pre>
1,983

edits