Seven-sided dice from five-sided dice: Difference between revisions

m
m (→‎{{header|REXX}}: changed a comment.)
 
(46 intermediate revisions by 19 users not shown)
Line 15:
<small>(Task adapted from an answer [http://stackoverflow.com/questions/90715/what-are-the-best-programming-puzzles-you-came-across here])</small>
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F dice5()
R random:(1..5)
 
F dice7() -> Int
V r = dice5() + dice5() * 5 - 6
R I r < 21 {(r % 7) + 1} E dice7()
 
F distcheck(func, repeats, delta)
V bin = DefaultDict[Int, Int]()
L 1..repeats
bin[func()]++
V target = repeats I/ bin.len
V deltacount = Int(delta / 100.0 * target)
assert(all(bin.values().map(count -> abs(@target - count) < @deltacount)), ‘Bin distribution skewed from #. +/- #.: #.’.format(target, deltacount, sorted(bin.items()).map((key, count) -> (key, @target - count))))
print(bin)
 
distcheck(dice5, 1000000, 1)
distcheck(dice7, 1000000, 1)</syntaxhighlight>
 
{{out}}
<pre>
DefaultDict([1 = 199586, 2 = 200094, 3 = 198933, 4 = 200824, 5 = 200563])
DefaultDict([1 = 142478, 2 = 142846, 3 = 143056, 4 = 142894, 5 = 143052, 6 = 143147, 7 = 142527])
</pre>
 
=={{header|Ada}}==
The specification of a package Random_57:
<langsyntaxhighlight Adalang="ada">package Random_57 is
 
type Mod_7 is mod 7;
Line 27 ⟶ 55:
-- a simple implementation
 
end Random_57;</langsyntaxhighlight>
Implementation of Random_57:
<langsyntaxhighlight Adalang="ada"> with Ada.Numerics.Discrete_Random;
 
package body Random_57 is
Line 85 ⟶ 113:
begin
Rand_5.Reset(Gen);
end Random_57;</langsyntaxhighlight>
A main program, using the Random_57 package:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Random_57;
 
procedure R57 is
Line 137 ⟶ 165:
Test( 1_000_000, Rand'Access, 0.02);
Test(10_000_000, Rand'Access, 0.01);
end R57;</langsyntaxhighlight>
{{out}}
<pre>
Line 170 ⟶ 198:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
C's version using no multiplications, divisions, or mod operators:
<langsyntaxhighlight lang="algol68">PROC dice5 = INT:
1 + ENTIER (5*random);
 
Line 204 ⟶ 232:
distcheck(dice5, 1000000, 5);
distcheck(dice7, 1000000, 7)
)</langsyntaxhighlight>
{{out}}
<pre>
Line 212 ⟶ 240:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">dice5()
{ Random, v, 1, 5
Return, v
Line 222 ⟶ 250:
IfLess v, 21, Return, (v // 3) + 1
}
}</langsyntaxhighlight>
<pre>Distribution check:
 
Line 239 ⟶ 267:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> MAXRND = 7
FOR r% = 2 TO 5
check% = FNdistcheck(FNdice7, 10^r%, 0.1)
Line 269 ⟶ 297:
IF bins%(i%)/(repet%/m%) < 1-delta s% += 1
NEXT
= s%</langsyntaxhighlight>
{{out}}
<pre>
Line 279 ⟶ 307:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">int rand5()
{
int r, rand_max = RAND_MAX - (RAND_MAX % 5);
Line 298 ⟶ 326:
printf(check(rand7, 7, 1000000, .05) ? "flat\n" : "not flat\n");
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 304 ⟶ 332:
flat
</pre>
 
=={{header|C sharp}}==
{{trans|Java}}
<syntaxhighlight lang="csharp">
using System;
 
public class SevenSidedDice
{
Random random = new Random();
static void Main(string[] args)
{
SevenSidedDice sevenDice = new SevenSidedDice();
Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven());
Console.Read();
}
int seven()
{
int v=21;
while(v>20)
v=five()+five()*5-6;
return 1+v%7;
}
int five()
{
return 1 + random.Next(5);
}
}</syntaxhighlight>
 
=={{header|C++}}==
This solution tries to minimize calls to the underlying d5 by reusing information from earlier calls.
<langsyntaxhighlight lang="cpp">template<typename F> class fivetoseven
{
public:
Line 355 ⟶ 413:
test_distribution(d5, 1000000, 0.001);
test_distribution(d7, 1000000, 0.001);
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
{{trans|Java}}
<lang csharp>
using System;
 
public class SevenSidedDice
{
Random random = new Random();
static void Main(string[] args)
{
SevenSidedDice sevenDice = new SevenSidedDice();
Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven());
Console.Read();
}
int seven()
{
int v=21;
while(v>20)
v=five()+five()*5-6;
return 1+v%7;
}
int five()
{
return 1 + random.Next(5);
}
}</lang>
 
=={{header|Clojure}}==
Uses the verify function defined in [[Verify distribution uniformity/Naive#Clojure]]
<langsyntaxhighlight Clojurelang="clojure">(def dice5 #(rand-int 5))
 
(defn dice7 []
Line 403 ⟶ 431:
(doseq [n [100 1000 10000] [num count okay?] (verify dice7 n)]
(println "Saw" num count "times:"
(if okay? "that's" " not") "acceptable"))</langsyntaxhighlight>
 
<pre>Saw 0 10 times: not acceptable
Line 429 ⟶ 457:
=={{header|Common Lisp}}==
{{trans|C}}
<langsyntaxhighlight lang="lisp">(defun d5 ()
(1+ (random 5)))
 
Line 435 ⟶ 463:
(loop for d55 = (+ (* 5 (d5)) (d5) -6)
until (< d55 21)
finally (return (1+ (mod d55 7)))))</langsyntaxhighlight>
 
<pre>> (check-distribution 'd7 1000)
Line 451 ⟶ 479:
=={{header|D}}==
{{trans|C++}}
<langsyntaxhighlight lang="d">import std.random;
import verify_distribution_uniformity_naive: distCheck;
 
Line 497 ⟶ 525:
distCheck(&fiveToSevenNaive, N, 1);
distCheck(&fiveToSevenSmart, N, 1);
}</langsyntaxhighlight>
{{out}}
<pre>1 80365
Line 524 ⟶ 552:
{{trans|Common Lisp}}
{{improve|E|Write dice7 in a prettier fashion and use the distribution checker once it's been written.}}
<langsyntaxhighlight lang="e">def dice5() {
return entropy.nextInt(5) + 1
}
Line 532 ⟶ 560:
while ((d55 := 5 * dice5() + dice5() - 6) >= 21) {}
return d55 %% 7 + 1
}</langsyntaxhighlight>
<langsyntaxhighlight lang="e">def bins := ([0] * 7).diverge()
for x in 1..1000 {
bins[dice7() - 1] += 1
}
println(bins.snapshot())</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
func dice5 .
return randint 5
.
func dice25 .
return (dice5 - 1) * 5 + dice5
.
func dice7a .
return dice25 mod1 7
.
func dice7b .
repeat
h = dice25
until h <= 21
.
return h mod1 7
.
numfmt 3 0
n = 1000000
len dist[] 7
#
proc checkdist . .
for i to len dist[]
h = dist[i] / n * 7
if abs (h - 1) > 0.01
bad = 1
.
dist[i] = 0
print h
.
if bad = 1
print "-> not uniform"
else
print "-> uniform"
.
.
#
for i to n
dist[dice7a] += 1
.
checkdist
#
print ""
for i to n
dist[dice7b] += 1
.
checkdist
</syntaxhighlight>
 
{{out}}
<pre>
1.122
1.118
1.121
1.117
0.840
0.842
0.840
-> not uniform
 
0.996
1.003
1.001
0.997
1.004
0.998
1.001
-> uniform
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Dice do
def dice5, do: :rand.uniform( 5 )
Line 557 ⟶ 656:
IO.inspect VerifyDistribution.naive( fun5, 1000000, 3 )
fun7 = fn -> Dice.dice7 end
IO.inspect VerifyDistribution.naive( fun7, 1000000, 3 )</langsyntaxhighlight>
 
{{out}}
Line 566 ⟶ 665:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( dice ).
 
Line 583 ⟶ 682:
dice7_small_enough( N ) when N < 21 -> N div 3 + 1;
dice7_small_enough( _N ) -> dice7().
</syntaxhighlight>
</lang>
 
{{out}}
Line 592 ⟶ 691:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: kernel random sequences assocs locals sorting prettyprint
math math.functions math.statistics math.vectors math.ranges ;
IN: rosetta-code.dice7
Line 648 ⟶ 747:
{ 1 10 100 1000 10000 100000 1000000 }
[| times | 0.02 7 [ dice7 ] times verify ] each
;</langsyntaxhighlight>
 
{{out}}
Line 669 ⟶ 768:
=={{header|Forth}}==
{{works with|GNU Forth}}
<langsyntaxhighlight lang="forth">require random.fs
 
: d5 5 random 1+ ;
Line 675 ⟶ 774:
: d7
begin d5 d5 2dup discard? while 2drop repeat
1- 5 * + 1- 7 mod 1+ ;</langsyntaxhighlight>
{{out}}
<pre>cr ' d7 1000000 7 1 check-distribution .
Line 690 ⟶ 789:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">module rand_mod
implicit none
 
Line 726 ⟶ 825:
call distcheck(rand7, samples, 0.001)
 
end program</langsyntaxhighlight>
{{out}}
<pre>Distribution Uniform
Line 737 ⟶ 836:
Distribution potentially skewed for bucket 6 Expected: 142857 Actual: 142163
Distribution potentially skewed for bucket 7 Expected: 142857 Actual: 142513</pre>
 
 
=={{header|FreeBASIC}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="freebasic">
Function dice5() As Integer
Return Int(Rnd * 5) + 1
End Function
 
Function dice7() As Integer
Dim As Integer temp
Do
temp = dice5() * 5 + dice5() -6
Loop Until temp < 21
Return (temp Mod 7) +1
End Function
 
Dim Shared As Ulongint n = 1000000
Print "Testing "; n; " times"
If Not(distCheck(n, 0.05)) Then Print "Test failed" Else Print "Test passed"
Sleep
</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de Liberty BASIC.
</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 794 ⟶ 919:
max, flatEnough = distCheck(dice7, 7, calls, 500)
fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 802 ⟶ 927:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">random = new Random()
 
int rand5() {
Line 814 ⟶ 939:
}
(raw % 7) + 1
}</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="groovy">def test = {
(1..6). each {
def counts = [0g, 0g, 0g, 0g, 0g, 0g, 0g]
Line 841 ⟶ 966:
=============="""
test(it)
}</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll;">TRIAL #1
Line 951 ⟶ 1,076:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import System.Random
import Data.List
 
Line 959 ⟶ 1,084:
let d7 = 5*d51+d52-6
if d7 > 20 then sevenFrom5Dice
else return $ 1 + d7 `mod` 7</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="haskell">*Main> replicateM 10 sevenFrom5Dice
[2,3,1,1,6,2,5,6,5,3]</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="haskell">*Main> mapM_ print .sort =<< distribCheck sevenFrom5Dice 1000000 3
(1,(142759,True))
(2,(143078,True))
Line 971 ⟶ 1,096:
(5,(142896,True))
(6,(143028,True))
(7,(143130,True))</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
{{trans|Ruby}}
Uses <code>verify_uniform</code> from [[Simple_Random_Distribution_Checker#Icon_and_Unicon|here]].
<syntaxhighlight lang="icon">
<lang Icon>
$include "distribution-checker.icn"
 
Line 992 ⟶ 1,117:
else write ("skewed")
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,008 ⟶ 1,133:
=={{header|J}}==
The first step is to create 7-sided dice rolls from 5-sided dice rolls (<code>rollD5</code>):
<langsyntaxhighlight lang="j">rollD5=: [: >: ] ?@$ 5: NB. makes a y shape array of 5s, "rolls" the array and increments.
roll2xD5=: [: rollD5 2 ,~ */ NB. rolls D5 twice for each desired D7 roll (y rows, 2 cols)
toBase10=: 5 #. <: NB. decrements and converts rows from base 5 to 10
Line 1,014 ⟶ 1,139:
groupin3s=: [: >. >: % 3: NB. increments, divides by 3 and takes ceiling
 
getD7=: groupin3s@keepGood@toBase10@roll2xD5</langsyntaxhighlight>
Here are a couple of variations on the theme that achieve the same result:
<langsyntaxhighlight lang="j">getD7b=: 0 8 -.~ 3 >.@%~ 5 #. [: <:@rollD5 2 ,~ ]
getD7c=: [: (#~ 7&>:) 3 >.@%~ [: 5&#.&.:<:@rollD5 ] , 2:</langsyntaxhighlight>
The trouble is that we probably don't have enough D7 rolls yet because we compressed out any double D5 rolls that evaluated to 21 or more. So we need to accumulate some more D7 rolls until we have enough. J has two types of verb definition - tacit (arguments not referenced) and explicit (more conventional function definitions) illustrated below:
 
Here's an explicit definition that accumulates rolls from <code>getD7</code>:
<langsyntaxhighlight lang="j">rollD7x=: monad define
n=. */y NB. product of vector y is total number of D7 rolls required
rolls=. '' NB. initialize empty noun rolls
Line 1,028 ⟶ 1,153:
end.
y $ rolls NB. shape the result according to the vector y
)</langsyntaxhighlight>
Here's a tacit definition that does the same thing:
<langsyntaxhighlight lang="j">getNumRolls=: [: >. 0.75 * */@[ NB. calc approx 3/4 of the required rolls
accumD7Rolls=: ] , getD7@getNumRolls NB. accumulates getD7 rolls
isNotEnough=: */@[ > #@] NB. checks if enough D7 rolls accumulated
 
rollD7t=: ] $ (accumD7Rolls ^: isNotEnough ^:_)&''</langsyntaxhighlight>
The <code>verb1 ^: verb2 ^:_</code> construct repeats <code>x verb1 y</code> while <code>x verb2 y</code> is true. It is like saying "Repeat accumD7Rolls while isNotEnough".
 
Example usage:
<langsyntaxhighlight lang="j"> rollD7t 10 NB. 10 rolls of D7
6 4 5 1 4 2 4 5 2 5
rollD7t 2 5 NB. 2 by 5 array of D7 rolls
Line 1,056 ⟶ 1,181:
1
($@rollD7x -: $@rollD7t) 2 3 5
1</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Python}}
<langsyntaxhighlight Javalang="java">import java.util.Random;
public class SevenSidedDice
{
Line 1,080 ⟶ 1,205:
return 1+rnd.nextInt(5);
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="javascript">function dice5()
{
return 1 + Math.floor(5 * Math.random());
Line 1,101 ⟶ 1,226:
distcheck(dice5, 1000000);
print();
distcheck(dice7, 1000000);</langsyntaxhighlight>
{{out}}
<pre>1 199792
Line 1,116 ⟶ 1,241:
6 142648
7 142619 </pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq.'''
 
In this entry, the results for both a low-entropy and a
high-entropy 5-sided die are shown. The former uses the computer's
clock as a not-very-good PRNG, and the latter uses /dev/random in accordance
with the following invocation:
<syntaxhighlight lang=sh>
#!/bin/bash
< /dev/random tr -cd '0-9' | fold -w 1 | jq -Mcnr -f dice.jq
</syntaxhighlight>
The results employ a two-tailed χ2-test at the 95% confidence level
according to which we are entitled to reject the null hypothesis of
uniform randomness if the χ2 statistic is less than 1.69 or greater
than 16.013, assuming the number of trials is large enough.
See https://www.itl.nist.gov/div898/handbook/eda/section3/eda3674.htm
 
'''dice.jq'''
<syntaxhighlight lang=jq>
# 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;
 
# Emit a stream of [value, frequency] pairs
def histogram(stream):
reduce stream as $s ({};
($s|type) as $t
| (if $t == "string" then $s else ($s|tojson) end) as $y
| .[$t][$y][0] = $s
| .[$t][$y][1] += 1 )
| .[][] ;
 
# sum of squares
def ss(s): reduce s as $x (0; . + ($x * $x));
 
def chiSquared($expected):
debug # show the actual frequencies
| ss( .[] - $expected ) / $expected;
 
# The high-entropy 5-sided die
def dice5: 1 + (5|prn);
 
# The low-entropy 5-sided die
def pseudo_dice5:
def r: (now * 100000 | floor) % 10;
null | until(. and (. < 5); r) | 1 + . ;
 
# The formal argument dice5 should behave like a 5-sided dice:
def dice7(dice5):
1 + ([limit(7; repeat(dice5))]|add % 7) ;
 
# Issue a report on the results of a sequence of $n trials using the specified dice
def report(dice; $n):
1.69 as $lower
| 16.013 as $upper
| [histogram( limit($n; repeat(dice)) ) | last]
| chiSquared($n/7) as $x2
| "The χ2 statistic for a trial of \($n) virtual tosses is \($x2).",
"Using a two-sided χ2-test with seven degrees of freedom (\($lower), \($upper)), it is reasonable to conclude that",
(if $x2 < $lower then "this is lower than would be expected for a fair die."
elif $x2 > $upper then "this is higher than would be expected for a fair die."
else "this is consistent with the die being fair."
end) ;
 
def report($n):
"Low-entropy die results:",
report(dice7(pseudo_dice5); $n),
"",
"High-entropy die results:",
report(dice7(dice5); $n) ;
 
report(70)
</syntaxhighlight>
{{output}}
<pre>
Low-entropy die results:
["DEBUG:",[19,14,6,18,7,5,1]]
The χ2 statistic for a trial of 70 virtual tosses is 29.2.
Using a two-sided χ2-test with seven degrees of freedom (1.69, 16.013), it is reasonable to conclude that
this is higher than would be expected for a fair die.
 
High-entropy die results:
["DEBUG:",[9,11,9,10,15,11,5]]
The χ2 statistic for a trial of 70 virtual tosses is 5.4.
Using a two-sided χ2-test with seven degrees of freedom (1.69, 16.013), it is reasonable to conclude that
this is consistent with the die being fair.
</pre>
'''Results for 1,000,000 trials:'''
<pre>
Low-entropy die results:
["DEBUG:",[41440,57949,15946,44821,117168,339337,383339]]
The χ2 statistic for a trial of 1000000 virtual tosses is 982157.0011039999.
Using a two-sided χ2-test with seven degrees of freedom (1.69, 16.013), it is reasonable to conclude that
this is higher than would be expected for a fair die.
 
High-entropy die results:
["DEBUG:",[142860,143087,142213,142065,143359,143494,142922]]
The χ2 statistic for a trial of 1000000 virtual tosses is 12.298347999999999.
Using a two-sided χ2-test with seven degrees of freedom (1.69, 16.013), it is reasonable to conclude that
this is consistent with the die being fair.
</pre>
 
=={{header|Julia}}==
 
<lang Julia>dice5() = rand(1:5)
<syntaxhighlight lang="julia">
using Random: seed!
seed!(1234) # for reproducibility
 
dice5() = rand(1:5)
 
function dice7()
while true
r = 5*dice5() + dice5() - 6
r < 21 ? (r%7a += 1) : dice7dice5()
b = dice5()
end</lang>
c = a + 5(b - 1)
Distribution check:
if c <= 21
<pre>julia> hist([dice5() for i=1:10^6])
return mod1(c, 7)
(0:1:5,[199932,200431,199969,199925,199743])
end
end
end
 
julia>rolls = hist([dice7() for i= in 1:10^6]100000)
roll_counts = Dict{Int,Int}()
(0:1:7,[142390,143032,142837,142999,142800,142642,143300])</pre>
for roll in rolls
roll_counts[roll] = get(roll_counts, roll, 0) + 1
end
foreach(println, sort(roll_counts))
 
</syntaxhighlight>
 
Output:
<pre>
1 => 14530
2 => 13872
3 => 14422
4 => 14425
5 => 14323
6 => 14315
7 => 14113
</pre>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.3
 
import java.util.Random
Line 1,175 ⟶ 1,433:
fun main(args: Array<String>) {
checkDist(::dice7, 1_400_000)
}</langsyntaxhighlight>
 
Sample output:
Line 1,195 ⟶ 1,453:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
n=1000000 '1000000 would take several minutes
print "Testing ";n;" times"
Line 1,219 ⟶ 1,477:
dice5=1+int(rnd(0)*5) '1..5: dice5
end function
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,237 ⟶ 1,495:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">dice5 = function() return math.random(5) end
 
function dice7()
Line 1,243 ⟶ 1,501:
if x > 20 then return dice7() end
return x%7 + 1
end</langsyntaxhighlight>
 
=={{header|MathematicaM2000 Interpreter}}==
We make a stack object (is reference type) and pass it as a closure to dice7 lambda function. For each dice7 we pop the top value of stack, and we add a fresh dice5 (random(1,5)) as last value of stack, so stack used as FIFO. Each time z has the sum of 7 random values.
<lang Mathematica>sevenFrom5Dice := (tmp$ = 5*RandomInteger[{1, 5}] + RandomInteger[{1, 5}] - 6;
 
If [tmp$ < 21, 1 + Mod[tmp$ , 7], sevenFrom5Dice])</lang>
We check for uniform numbers using +-5% from expected value.
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Def long i, calls, max, min
s=stack:=random(1,5),random(1,5), random(1,5), random(1,5), random(1,5), random(1,5), random(1,5)
z=0: for i=1 to 7 { z+=stackitem(s, i)}
dice7=lambda z, s -> {
=((z-1) mod 7)+1 : stack s {z-=Number : data random(1,5): z+=Stackitem(7)}
}
Dim count(1 to 7)=0& ' long type
calls=700000
p=0.05
IsUniform=lambda max=calls/7*(1+p), min=calls/7*(1-p) (a)->{
if len(a)=0 then =false : exit
=false
m=each(a)
while m
if array(m)<min or array(m)>max then break
end while
=true
}
For i=1 to calls {count(dice7())++}
max=count()#max()
expected=calls div 7
min=count()#min()
for i=1 to 7
document doc$=format$("{0}{1::-7}",i,count(i))+{
}
Next i
doc$=format$("min={0} expected={1} max={2}", min, expected, max)+{
}+format$("Verify Uniform:{0}", if$(IsUniform(count())->"uniform", "skewed"))+{
}
Print
report doc$
clipboard doc$
}
CheckIt
</syntaxhighlight>
 
{{out}}
<pre style="height:30ex;overflow:scroll">
1 9865
2 10109
3 9868
4 9961
5 9936
6 9922
7 10339
min=9865 expected=10000 max=10339
Verify Uniform:uniform
 
 
1 100214
2 100336
3 100049
4 99505
5 99951
6 99729
7 100216
min=99505 expected=100000 max=100336
Verify Uniform:uniform
</pre >
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">sevenFrom5Dice := (tmp$ = 5*RandomInteger[{1, 5}] + RandomInteger[{1, 5}] - 6;
If [tmp$ < 21, 1 + Mod[tmp$ , 7], sevenFrom5Dice])</syntaxhighlight>
<pre>CheckDistribution[sevenFrom5Dice, 1000000, 5]
->Expected: 142857., Generated :{142206,142590,142650,142693,142730,143475,143656}
->"Flat"</pre>
 
=={{header|Nim}}==
We use the distribution checker from task [[Simple Random Distribution Checker#Nim|Simple Random Distribution Checker]].
<syntaxhighlight lang="nim">import random, tables
 
 
proc dice5(): int = rand(1..5)
 
 
proc dice7(): int =
while true:
let val = 5 * dice5() + dice5() - 6
if val < 21:
return val div 3 + 1
 
 
proc checkDist(f: proc(): int; repeat: Positive; tolerance: float) =
 
var counts: CountTable[int]
for _ in 1..repeat:
counts.inc f()
 
let expected = (repeat / counts.len).toInt # Rounded to nearest.
let allowedDelta = (expected.toFloat * tolerance / 100).toInt
var maxDelta = 0
for val, count in counts.pairs:
let d = abs(count - expected)
if d > maxDelta: maxDelta = d
 
let status = if maxDelta <= allowedDelta: "passed" else: "failed"
echo "Checking ", repeat, " values with a tolerance of ", tolerance, "%."
echo "Random generator ", status, " the uniformity test."
echo "Max delta encountered = ", maxDelta, " Allowed delta = ", allowedDelta
 
 
when isMainModule:
import random
randomize()
checkDist(dice7, 1_000_000, 0.5)</syntaxhighlight>
 
{{out}}
<pre>Checking 1000000 values with a tolerance of 0.5%.
Random generator passed the uniformity test.
Max delta encountered = 552 Allowed delta = 714</pre>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let dice5() = 1 + Random.int 5 ;;
 
let dice7 =
Line 1,269 ⟶ 1,637:
in
aux
;;</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">dice5()=random(5)+1;
 
dice7()={
Line 1,278 ⟶ 1,646:
while((t=dice5()*5+dice5()) > 21,);
(t+2)\3
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
A console application in Free Pascal, created with the Lazarus IDE.
 
The algorithm suggested in the task description requires on average 50/21 (about 2.38) calls to Dice5 for each call to Dice7. See the link in the VBA solution for a discussion on how to reduce this ratio. It cannot be made less than log_5(7) = 1.209062. The algorithm below is based on Rex Kerr's solution, and requires about 1.2185 calls to Dice5 per call to Dice7. Runtime is about 60% of that for the suggested simple algorithm.
 
A chi-squared test can be carried out with the help of statistical tables, and is preferred here to an arbitrary "naive" test.
<syntaxhighlight lang="pascal">
unit UConverter;
(*
Defines a converter object to output uniformly distributed random integers 1..7,
given a source of uniformly distributed random integers 1..5.
*)
interface
 
type
TFace5 = 1..5;
TFace7 = 1..7;
TDice5 = function() : TFace5;
 
type TConverter = class( TObject)
private
fDigitBuf: array [0..19] of integer; // holds digits in base 7
fBufCount, fBufPtr : integer;
fDice5 : TDice5; // passed-in generator for integers 1..5
fNrDice5 : int64; // diagnostics, counts calls to fDice5
public
constructor Create( aDice5 : TDice5);
procedure Reset();
function Dice7() : TFace7;
property NrDice5 : int64 read fNrDice5;
end;
 
implementation
 
constructor TConverter.Create( aDice5 : TDice5);
begin
inherited Create();
fDice5 := aDice5;
self.Reset();
end;
 
procedure TConverter.Reset();
begin
fBufCount := 0;
fBufPtr := 0;
fNrDice5 := 0;
end;
 
function TConverter.Dice7() : TFace7;
var
digit_holder, temp : int64;
j : integer;
begin
if fBufPtr = fBufCount then begin // if no more in buffer
fBufCount := 0;
fBufPtr := 0;
repeat // first time through will usually be enough
// Use supplied fDice5 to generate random 23-digit integer in base 5.
digit_holder := 0;
for j := 0 to 22 do begin
digit_holder := 5*digit_holder + fDice5() - 1;
inc( fNrDice5);
end;
// Convert to 20-digit number in base 7. (A simultaneous DivMod
// procedure would be neater, but isn't available for int64.)
for j := 0 to 19 do begin
temp := digit_holder div 7;
fDigitBuf[j] := digit_holder - 7*temp;
digit_holder := temp;
end;
// Maximum possible is 5^23 - 1, which is 10214646460315315132 in base 7.
// If leading digit in base 7 is 0 then low 19 digits are random.
// Else number begins with 100, 101, or 102; and if with
// 100 or 101 then low 17 digits are random. And so on.
if fDigitBuf[19] = 0 then fBufCount := 19
else if fDigitBuf[17] < 2 then fBufCount := 17
else if fDigitBuf[16] = 0 then fBufCount := 16;
// We could go on but that will do.
until fBufCount > 0;
end; // if no more in buffer
result := fDigitBuf[fBufPtr] + 1;
inc( fBufPtr);
end;
end.
 
program Dice_SevenFromFive;
(*
Demonstrates use of the UConverter unit.
*)
{$mode objfpc}{$H+}
uses
SysUtils, UConverter;
 
function Dice5() : UConverter.TFace5;
begin
result := Random(5) + 1; // Random(5) returns 0..4
end;
 
// Percentage points of the chi-squared distribution, 6 degrees of freedom.
// From New Cambridge Statistical Tables, 2nd edn, pp. 40-41.
const
CHI_SQ_6df_95pc = 1.635;
CHI_SQ_6df_05pc = 12.59;
 
// Main routine
var
nrThrows, j, k : integer;
nrFaces : array [1..7] of integer;
X2, expected, diff : double;
conv : UConverter.TConverter;
begin
conv := UConverter.TConverter.Create( @Dice5);
WriteLn( 'Enter 0 throws to quit');
repeat
WriteLn(''); Write( 'Number of throws (0 to quit): ');
ReadLn( nrThrows);
if nrThrows = 0 then begin
conv.Free();
exit;
end;
conv.Reset(); // clears count of calls to Dice5
for k := 1 to 7 do nrFaces[k] := 0;
for j := 1 to nrThrows do begin
k := conv.Dice7();
inc( nrFaces[k]);
end;
WriteLn('');
WriteLn( SysUtils.Format( 'Number of throws = %10d', [nrThrows]));
WriteLn( SysUtils.Format( 'Calls to Dice5 = %10d', [conv.NrDice5]));
for k := 1 to 7 do
WriteLn( SysUtils.Format( ' Number of %d''s = %10d', [k, nrFaces[k]]));
 
// Calculation of chi-squared
expected := nrThrows/7.0;
X2 := 0.0;
for k := 1 to 7 do begin
diff := nrFaces[k] - expected;
X2 := X2 + diff*diff/expected;
end;
WriteLn( SysUtils.Format( 'X^2 = %0.3f on 6 degrees of freedom', [X2]));
if X2 < CHI_SQ_6df_95pc then WriteLn( 'Too regular at 5% level')
else if X2 > CHI_SQ_6df_05pc then WriteLn( 'Too irregular at 5% level')
else WriteLn( 'Satisfactory at 5% level')
until false;
end.
</syntaxhighlight>
{{out}}
<pre>
Number of throws = 100000000
Calls to Dice5 = 121846341
Number of 1's = 14282807
Number of 2's = 14282277
Number of 3's = 14288393
Number of 4's = 14285486
Number of 5's = 14289379
Number of 6's = 14291053
Number of 7's = 14280605
X^2 = 6.687 on 6 degrees of freedom
Satisfactory at 5% level
</pre>
 
=={{header|Perl}}==
Using dice5 twice to generate numbers in the range 0 to 24. If we consider these modulo 8 and re-call if we get zero, we have eliminated 4 cases and created the necessary number in the range from 1 to 7.
<langsyntaxhighlight lang="perl">sub dice5 { 1+int rand(5) }
 
sub dice7 {
Line 1,294 ⟶ 1,824:
$count7{dice7()}++ for 1..$n;
printf "%s: %5.2f%%\n", $_, 100*($count7{$_}/$n*7-1) for sort keys %count7;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,306 ⟶ 1,836:
</pre>
 
=={{header|Perl 6Phix}}==
replace rand7() in [[Verify_distribution_uniformity/Naive#Phix]] with:
{{works with|Rakudo Star|2010.09}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
Since rakudo is still pretty slow, we've done some interesting bits of optimization.
<span style="color: #008080;">function</span> <span style="color: #000000;">dice5</span><span style="color: #0000FF;">()</span>
We factor out the range object construction so that it doesn't have to be recreated each time, and we sneakily <em>subtract</em> the 1's from the 5's, which takes us back to 0 based without having to subtract 6.
<span style="color: #008080;">return</span> <span style="color: #7060A8;">rand</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<lang perl6>my $d5 = 1..5;
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sub d5() { $d5.roll; } # 1d5
 
<span style="color: #008080;">function</span> <span style="color: #000000;">dice7</span><span style="color: #0000FF;">()</span>
sub d7() {
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
my $flat = 21;
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dice5</span><span style="color: #0000FF;">()*</span><span style="color: #000000;">5</span><span style="color: #0000FF;">+</span><span style="color: #000000;">dice5</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">3</span> <span style="color: #000080;font-style:italic;">-- ( ie 3..27, but )</span>
$flat = 5 * d5() - d5() until $flat < 21;
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;"><</span><span style="color: #000000;">24</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">/</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #000080;font-style:italic;">-- (only 3..23 useful)</span>
$flat % 7 + 1;
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
}</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
Here's the test. We use a C-style for loop, except it's named <code>loop</code>, because it's currently faster than the other loops--and, er, doesn't segfault the GC on a million iterations...
<!--</syntaxhighlight>-->
<lang perl6>my @dist;
my $n = 1_000_000;
my $expect = $n / 7;
 
loop ($_ = $n; $n; --$n) { @dist[d7()]++; }
 
say "Expect\t",$expect.fmt("%.3f");
for @dist.kv -> $i, $v {
say "$i\t$v\t" ~ (($v - $expect)/$expect*100).fmt("%+.2f%%") if $v;
}</lang>
{{out}}
<pre>Expect 142857.143
1000000 iterations: flat
1 142835 -0.02%
</pre>
2 143021 +0.11%
3 142771 -0.06%
4 142706 -0.11%
5 143258 +0.28%
6 142485 -0.26%
7 142924 +0.05%</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de dice5 ()
(rand 1 5) )
 
Line 1,346 ⟶ 1,862:
(use R
(until (> 21 (setq R (+ (* 5 (dice5)) (dice5) -6))))
(inc (% R 7)) ) )</langsyntaxhighlight>
{{out}}
<pre>: (let R NIL
Line 1,355 ⟶ 1,871:
=={{header|PureBasic}}==
{{trans|Lua}}
<langsyntaxhighlight PureBasiclang="purebasic">Procedure dice5()
ProcedureReturn Random(4) + 1
EndProcedure
Line 1,368 ⟶ 1,884:
ProcedureReturn x % 7 + 1
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from random import randint
 
def dice5():
Line 1,378 ⟶ 1,894:
def dice7():
r = dice5() + dice5() * 5 - 6
return (r % 7) + 1 if r < 21 else dice7()</langsyntaxhighlight>
Distribution check using [[Simple Random Distribution Checker#Python|Simple Random Distribution Checker]]:
<pre>>>> distcheck(dice5, 1000000, 1)
Line 1,385 ⟶ 1,901:
{1: 142853, 2: 142576, 3: 143067, 4: 142149, 5: 143189, 6: 143285, 7: 142881}
</pre>
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ 5 random 1+ ] is dice5 ( --> n )
=={{header|Racket}}==
<lang Racket>
#lang racket
(define (dice5) (add1 (random 5)))
 
[ dice5 5 *
(define (dice7)
dice5 + 6 -
(define res (+ (* 5 (dice5)) (dice5) -6))
[ table
(if (< res 21) (+ 1 (modulo res 7)) (dice7)))
0 0 0 0 1
</lang>
1 1 2 2 2
3 3 3 4 4
4 5 5 5 6
6 6 7 7 7 ]
dup 0 = iff
drop again ] is dice7 ( --> n )</syntaxhighlight>
 
{{out}}
Checking the uniformity using math library:
 
<code>distribution</code> is defined at [[Verify distribution uniformity/Naive#Quackery]].
<lang racket>
 
-> (require math/statistics)
<pre>/O> ' dice7 1000000 666 distribution
-> (samples->hash (for/list ([i 700000]) (dice7)))
...
'#hash((7 . 100392)
[ 143196 142815 143451 142716 142964 142300 142558 ]
(6 . 100285)
 
(5 . 99774)
Stack empty.</pre>
(4 . 100000)
(3 . 100000)
(2 . 99927)
(1 . 99622))
</lang>
 
=={{header|R}}==
5-sided die.
<langsyntaxhighlight lang="r">dice5 <- function(n=1) sample(5, n, replace=TRUE)</langsyntaxhighlight>
Simple but slow 7-sided die, using a while loop.
<langsyntaxhighlight lang="r">dice7.while <- function(n=1)
{
score <- numeric()
Line 1,424 ⟶ 1,940:
score
}
system.time(dice7.while(1e6)) # longer than 4 minutes</langsyntaxhighlight>
More complex, but much faster vectorised version.
<langsyntaxhighlight lang="r">dice7.vec <- function(n=1, checkLength=TRUE)
{
morethan2n <- 3 * n + 10 + (n %% 2) #need more than 2*n samples, because some are discarded
Line 1,443 ⟶ 1,959:
} else score
}
system.time(dice7.vec(1e6)) # ~1 sec</langsyntaxhighlight>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(define (dice5) (add1 (random 5)))
 
(define (dice7)
(define res (+ (* 5 (dice5)) (dice5) -6))
(if (< res 21) (+ 1 (modulo res 7)) (dice7)))
</syntaxhighlight>
 
Checking the uniformity using math library:
 
<syntaxhighlight lang="racket">
-> (require math/statistics)
-> (samples->hash (for/list ([i 700000]) (dice7)))
'#hash((7 . 100392)
(6 . 100285)
(5 . 99774)
(4 . 100000)
(3 . 100000)
(2 . 99927)
(1 . 99622))
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
 
<syntaxhighlight lang="raku" line>my $d5 = 1..5;
sub d5() { $d5.roll; } # 1d5
 
sub d7() {
my $flat = 21;
$flat = 5 * d5() - d5() until $flat < 21;
$flat % 7 + 1;
}
 
# Testing
my @dist;
my $n = 1_000_000;
my $expect = $n / 7;
 
loop ($_ = $n; $n; --$n) { @dist[d7()]++; }
 
say "Expect\t",$expect.fmt("%.3f");
for @dist.kv -> $i, $v {
say "$i\t$v\t" ~ (($v - $expect)/$expect*100).fmt("%+.2f%%") if $v;
}</syntaxhighlight>
{{out}}
<pre>Expect 142857.143
1 143088 +0.16%
2 143598 +0.52%
3 141741 -0.78%
4 142832 -0.02%
5 143040 +0.13%
6 142988 +0.09%
7 142713 -0.10%
</pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program simulates a 7─sided die based on a 5─sided throw for a number of trials. */
parse arg trials sample seed . /*obtain optional arguments from the CL*/
if trials=='' | trials="," then trials= 1 1 /*Not specified? Then use the default.*/
if sample=='' | sample="," then sample=1000000 1000000 /* " " " " " " */
if datatype(seed, 'W') then call random ,,seed /*Integer? Then use it as a RAND seed.*/
L= length(trials) /* [↑] one million samples to be used.*/
 
do #=1 for trials; die.=0 /*performs the number of desired trials*/
do #=1 for trials; die.= 0 /*performs the number of desired trials*/
k=0
k= 0
do until k==sample; r=5 * random(1, 5) + random(1, 5) - 6
do until k==sample; if r>20= 5 * random(1, 5) + random(1, 5) - then iterate6
k=k+1; if r=r>20 // 7 + 1; die.r=die.r +then 1iterate
k= k + end1; r= r /*until*/ 7 + 1; die.r= die.r + 1
end /*until*/
say
say
expect=sample%7
expect= sample % 7
say center('trial:'right(#, 4) " " sample 'samples, expect='expect, 80, "─")
say center('trial:' right(#, L) " " sample 'samples, expect' expect, 80, "─")
 
do j=1 for 7
say ' side' j "had " die.j ' occurrences',
' difference from expected:'right(die.j - expect, length(sample) )
end /*j*/
end /*#*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 11 </tt>}}
 
Line 1,472 ⟶ 2,048:
 
<pre style="font-size:84%;height:71ex">
─────────────────trial──────────────────trial: 1 1000000 samples, expect= 142857──────────────────
side 1 had 142990142076 occurrences difference from expected: 133-781
side 2 had 142811143053 occurrences difference from expected: -46196
side 3 had 143348142342 occurrences difference from expected: 491-515
side 4 had 143219142633 occurrences difference from expected: 362-224
side 5 had 142717143024 occurrences difference from expected: -140 167
side 6 had 141951143827 occurrences difference from expected: -906 970
side 7 had 142964143045 occurrences difference from expected: 107188
 
─────────────────trial──────────────────trial: 2 1000000 samples, expect= 142857──────────────────
side 1 had 142707143470 occurrences difference from expected: -150 613
side 2 had 142512142998 occurrences difference from expected: -345 141
side 3 had 143038142654 occurrences difference from expected: 181-203
side 4 had 143268142545 occurrences difference from expected: 411-312
side 5 had 142629142452 occurrences difference from expected: -228405
side 6 had 142902143144 occurrences difference from expected: 45287
side 7 had 142944142737 occurrences difference from expected: 87-120
 
─────────────────trial──────────────────trial: 3 1000000 samples, expect= 142857──────────────────
side 1 had 142743142773 occurrences difference from expected: -11484
side 2 had 142674143198 occurrences difference from expected: -183 341
side 3 had 142834142296 occurrences difference from expected: -23561
side 4 had 142668142804 occurrences difference from expected: -18953
side 5 had 143108142897 occurrences difference from expected: 251 40
side 6 had 142727142382 occurrences difference from expected: -130475
side 7 had 143246143650 occurrences difference from expected: 389793
 
─────────────────trial──────────────────trial: 4 1000000 samples, expect= 142857──────────────────
side 1 had 142575143150 occurrences difference from expected: -282 293
side 2 had 143139142635 occurrences difference from expected: 282-222
side 3 had 142618142763 occurrences difference from expected: -23994
side 4 had 142647142853 occurrences difference from expected: -2104
side 5 had 142204143132 occurrences difference from expected: -653 275
side 6 had 143228142403 occurrences difference from expected: 371-454
side 7 had 143589143064 occurrences difference from expected: 732207
 
─────────────────trial──────────────────trial: 5 1000000 samples, expect= 142857──────────────────
side 1 had 142539143041 occurrences difference from expected: -318 184
side 2 had 143490142701 occurrences difference from expected: 633-156
side 3 had 142261143416 occurrences difference from expected: -596 559
side 4 had 142755142097 occurrences difference from expected: -102760
side 5 had 142976142451 occurrences difference from expected: 119-406
side 6 had 143188143332 occurrences difference from expected: 331475
side 7 had 142791142962 occurrences difference from expected: -66105
 
─────────────────trial──────────────────trial: 6 1000000 samples, expect= 142857──────────────────
side 1 had 142706142502 occurrences difference from expected: -151355
side 2 had 142344142429 occurrences difference from expected: -513428
side 3 had 143243143146 occurrences difference from expected: 386289
side 4 had 143626142791 occurrences difference from expected: 769-66
side 5 had 142555143271 occurrences difference from expected: -302 414
side 6 had 142530143415 occurrences difference from expected: -327 558
side 7 had 142996142446 occurrences difference from expected: 139-411
 
─────────────────trial──────────────────trial: 7 1000000 samples, expect= 142857──────────────────
side 1 had 142901142700 occurrences difference from expected: 44-157
side 2 had 142950142691 occurrences difference from expected: 93-166
side 3 had 143147143067 occurrences difference from expected: 290210
side 4 had 142081141562 occurrences difference from expected: -7761295
side 5 had 143423143316 occurrences difference from expected: 566459
side 6 had 141965143150 occurrences difference from expected: -892 293
side 7 had 143533143514 occurrences difference from expected: 676657
 
─────────────────trial──────────────────trial: 8 1000000 samples, expect= 142857──────────────────
side 1 had 142818142362 occurrences difference from expected: -39495
side 2 had 142681143298 occurrences difference from expected: -176 441
side 3 had 142886142639 occurrences difference from expected: 29-218
side 4 had 142975142811 occurrences difference from expected: 118-46
side 5 had 142987143275 occurrences difference from expected: 130418
side 6 had 142781142765 occurrences difference from expected: -7692
side 7 had 142872142850 occurrences difference from expected: 15-7
 
─────────────────trial──────────────────trial: 9 1000000 samples, expect= 142857──────────────────
side 1 had 143501143508 occurrences difference from expected: 644651
side 2 had 142404142650 occurrences difference from expected: -453207
side 3 had 142882142614 occurrences difference from expected: 25-243
side 4 had 143051142916 occurrences difference from expected: 194 59
side 5 had 142479142944 occurrences difference from expected: -378 87
side 6 had 142664143129 occurrences difference from expected: -193 272
side 7 had 143019142239 occurrences difference from expected: 162-618
 
─────────────────trial──────────────────trial: 10 1000000 samples, expect= 142857──────────────────
side 1 had 142945142455 occurrences difference from expected: 88-402
side 2 had 143142143112 occurrences difference from expected: 285255
side 3 had 142843143435 occurrences difference from expected: -14578
side 4 had 143043142704 occurrences difference from expected: 186-153
side 5 had 142558142376 occurrences difference from expected: -299481
side 6 had 142834142721 occurrences difference from expected: -23136
side 7 had 142635143197 occurrences difference from expected: -222 340
 
─────────────────trial──────────────────trial: 11 1000000 samples, expect= 142857──────────────────
side 1 had 143248142967 occurrences difference from expected: 391110
side 2 had 142878142204 occurrences difference from expected: 21-653
side 3 had 142229142993 occurrences difference from expected: -628 136
side 4 had 142902142797 occurrences difference from expected: 45-60
side 5 had 142685143081 occurrences difference from expected: -172 224
side 6 had 143214142711 occurrences difference from expected: 357-146
side 7 had 142844143247 occurrences difference from expected: -13390
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Seven-sided dice from five-sided dice
 
for n = 1 to 20
d = dice7()
see "" + d + " "
next
see nl
 
func dice7()
x = dice5() * 5 + dice5() - 6
if x > 20
return dice7()
ok
dc = x % 7 + 1
return dc
 
func dice5()
rnd = random(4) + 1
return rnd
</syntaxhighlight>
Output:
<pre>
7 6 3 5 2 2 7 1 2 7 3 7 4 4 4 2 3 2 6 1
</pre>
 
=={{header|RPL}}==
<code>UNIF?</code> is defined at [[Verify distribution uniformity/Naive#RPL|Verify distribution uniformity/Naive]]
{{works with|Halcyon Calc|4.2.7}}
≪ ≪ RAND 5 * CEIL ≫ → dice5
≪ '''WHILE'''
dice5 EVAL 5 *
dice5 EVAL 6 - +
DUP 21 ≥
'''REPEAT''' DROP '''END'''
7 MOD 1 +
≫ ≫ '<span style="color:blue">DICE7</span>' STO
 
≪ <span style="color:blue">DICE7</span> ≫ 100000 .1 <span style="color:blue">UNIF?</span>
{{out}}
<pre>
1: [ 14557 14245 14255 14400 14224 14151 14168 ]
</pre>
Watchdog timer limits the loop to 100,000 items.
 
=={{header|Ruby}}==
{{trans|Tcl}}
Uses <code>distcheck</code> from [[Simple_Random_Distribution_Checker#Ruby|here]].
<langsyntaxhighlight lang="ruby">require './distcheck.rb'
 
def d5
Line 1,589 ⟶ 2,211:
 
distcheck(1_000_000) {d5}
distcheck(1_000_000) {d7}</langsyntaxhighlight>
 
{{out}}
Line 1,604 ⟶ 2,226:
6 142605
7 142811</pre>
 
=={{header|Scala}}==
{{Out}}Best seen running in your browser either by [https://scalafiddle.io/sf/3RNtNEC/0 ScalaFiddle (ES aka JavaScript, non JVM)] or [https://scastie.scala-lang.org/Y5qSeW52QiC40l5vJCUMRA Scastie (remote JVM)].
<syntaxhighlight lang="scala">import scala.util.Random
 
object SevenSidedDice extends App {
private val rnd = new Random
 
private def seven = {
var v = 21
 
def five = 1 + rnd.nextInt(5)
 
while (v > 20) v = five + five * 5 - 6
1 + v % 7
}
 
println("Random number from 1 to 7: " + seven)
 
}</syntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func dice5 { 1 + 5.rand.int }
 
func dice7 {
Line 1,622 ⟶ 2,264:
count7.keys.sort.each { |k|
printf("%s: %5.2f%%\n", k, 100*(count7{k}/n * 7 - 1));
}</langsyntaxhighlight>
 
{{out}}
<pre>1: -0.00%
1: -0.00%
2: 0.02%
3: 0.23%
Line 1,632 ⟶ 2,272:
5: -0.23%
6: -0.54%
7: 0.10%</pre>
</pre>
 
=={{header|Tcl}}==
Any old D&D hand will know these as a D5 and a D7...
<langsyntaxhighlight lang="tcl">proc D5 {} {expr {1 + int(5 * rand())}}
 
proc D7 {} {
Line 1,646 ⟶ 2,285:
}
}
}</langsyntaxhighlight>
Checking:
<span class="sy0">%</span> distcheck D5 <span class="nu0">1000000</span>
Line 1,652 ⟶ 2,291:
<span class="sy0">%</span> distcheck D7 <span class="nu0">1000000</span>
1 143121 2 142383 3 143353 4 142811 5 142172 6 143291 7 142869
 
=={{header|VBA}}==
The original StackOverflow page doesn't exist any longer. Luckily [https://web.archive.org/web/20100730055051/http://stackoverflow.com:80/questions/137783/given-a-function-which-produces-a-random-integer-in-the-range-1-to-5-write-a-fun archive.org] exists.
<syntaxhighlight lang="vb">Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean
'Returns true if the observed frequencies pass the Pearson Chi-squared test at the required significance level.
Dim Total As Long, Ei As Long, i As Integer
Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double
Debug.Print "[1] ""Data set:"" ";
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
Total = Total + ObservationFrequencies(i)
Debug.Print ObservationFrequencies(i); " ";
Next i
DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)
'This is exactly the number of different categories minus 1
Ei = Total / (DegreesOfFreedom + 1)
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei
Next i
p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)
Debug.Print
Debug.Print "Chi-squared test for given frequencies"
Debug.Print "X-squared ="; Format(ChiSquared, "0.0000"); ", ";
Debug.Print "df ="; DegreesOfFreedom; ", ";
Debug.Print "p-value = "; Format(p_value, "0.0000")
Test4DiscreteUniformDistribution = p_value > Significance
End Function
Private Function Dice5() As Integer
Dice5 = Int(5 * Rnd + 1)
End Function
Private Function Dice7() As Integer
Dim i As Integer
Do
i = 5 * (Dice5 - 1) + Dice5
Loop While i > 21
Dice7 = i Mod 7 + 1
End Function
Sub TestDice7()
Dim i As Long, roll As Integer
Dim Bins(1 To 7) As Variant
For i = 1 To 1000000
roll = Dice7
Bins(roll) = Bins(roll) + 1
Next i
Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(Bins, 0.05); """"
End Sub</syntaxhighlight>
{{out}}<pre>[1] "Data set:" 142418 142898 142940 142573 143030 143139 143002
Chi-squared test for given frequencies
X-squared =2.8870, df = 6 , p-value = 0.8229
[1] "Uniform? True"
</pre>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">Option Explicit
 
function dice5
Line 1,666 ⟶ 2,355:
loop until j < 21
dice7 = j mod 7 + 1
end function</langsyntaxhighlight>
 
=={{header|Verilog}}==
<langsyntaxhighlight lang="verilog">
 
/// @Author: Alexandre Felipe (o.alexandre.felipe@gmail.com)
/// @Date: 2017-May-10
 
///////////////////////////////////////////////////////////////////////////////
Line 1,732 ⟶ 2,418:
/// seven_sided_dice : ///
/// Synthsizeable module that using a 5 sided dice as a black box ///
/// is able to reproduce tehthe outcomes if a 7-sided dice ///
///////////////////////////////////////////////////////////////////////////////
module seven_sided_dice(
Line 1,796 ⟶ 2,482:
end
endmodule
</syntaxhighlight>
</lang>
 
Compiling with Icarus Verilog
Line 1,818 ⟶ 2,504:
5 with probability 1/7 + ( 51 ppm)
6 with probability 1/7 - ( 109 ppm)
</pre>
 
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-sort}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "random" for Random
import "./sort" for Sort
import "./fmt" for Fmt
 
var r = Random.new()
 
var dice5 = Fn.new { r.int(1, 6) }
 
var dice7 = Fn.new {
while (true) {
var t = (dice5.call() - 1) * 5 + dice5.call() - 1
if (t < 21) return 1 + (t/3).floor
}
}
 
var checkDist = Fn.new { |gen, nRepeats, tolerance|
var occurs = {}
for (i in 1..nRepeats) {
var d = gen.call()
occurs[d] = occurs.containsKey(d) ? occurs[d] + 1 : 1
}
var expected = (nRepeats/occurs.count).floor
var maxError = (expected * tolerance / 100).floor
System.print("Repetitions = %(nRepeats), Expected = %(expected)")
System.print("Tolerance = %(tolerance)\%, Max Error = %(maxError)\n")
System.print("Integer Occurrences Error Acceptable")
var f = " $d $5d $5d $s"
var allAcceptable = true
var cmp = Fn.new { |me1, me2| (me1.key - me2.key).sign }
occurs = occurs.toList
Sort.insertion(occurs, cmp)
for (me in occurs) {
var k = me.key
var v = me.value
var error = (v - expected).abs
var acceptable = (error <= maxError) ? "Yes" : "No"
if (acceptable == "No") allAcceptable = false
Fmt.print(f, k, v, error, acceptable)
}
System.print("\nAcceptable overall: %(allAcceptable ? "Yes" : "No")")
}
 
checkDist.call(dice7, 1400000, 0.5)</syntaxhighlight>
 
{{out}}
<pre>
Repetitions = 1400000, Expected = 200000
Tolerance = 0.5%, Max Error = 1000
 
Integer Occurrences Error Acceptable
1 199744 256 Yes
2 199678 322 Yes
3 200254 254 Yes
4 199903 97 Yes
5 200080 80 Yes
6 200070 70 Yes
7 200271 271 Yes
 
Acceptable overall: Yes
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var die5=(1).random.fp(6); // [1..5]
fcn die7{ while((r:=5*die5() + die5())>=27){} r/3-1 }
 
Line 1,832 ⟶ 2,583:
 
println("Looking for ",100.0/7,"%");
rtest(0d1_000_000);</langsyntaxhighlight>
{{out}}
<pre>
1,969

edits