Seven-sided dice from five-sided dice: Difference between revisions
Seven-sided dice from five-sided dice (view source)
Revision as of 13:58, 28 August 2022
, 1 year agosyntax highlighting fixup automation
(Added solution for Free Pascal (Lazarus)) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 19:
{{trans|Python}}
<
R random:(1..5)
Line 36:
distcheck(dice5, 1000000, 1)
distcheck(dice7, 1000000, 1)</
{{out}}
Line 46:
=={{header|Ada}}==
The specification of a package Random_57:
<
type Mod_7 is mod 7;
Line 55:
-- a simple implementation
end Random_57;</
Implementation of Random_57:
<
package body Random_57 is
Line 113:
begin
Rand_5.Reset(Gen);
end Random_57;</
A main program, using the Random_57 package:
<
procedure R57 is
Line 165:
Test( 1_000_000, Rand'Access, 0.02);
Test(10_000_000, Rand'Access, 0.01);
end R57;</
{{out}}
<pre>
Line 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:
<
1 + ENTIER (5*random);
Line 232:
distcheck(dice5, 1000000, 5);
distcheck(dice7, 1000000, 7)
)</
{{out}}
<pre>
Line 240:
=={{header|AutoHotkey}}==
<
{ Random, v, 1, 5
Return, v
Line 250:
IfLess v, 21, Return, (v // 3) + 1
}
}</
<pre>Distribution check:
Line 267:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
FOR r% = 2 TO 5
check% = FNdistcheck(FNdice7, 10^r%, 0.1)
Line 297:
IF bins%(i%)/(repet%/m%) < 1-delta s% += 1
NEXT
= s%</
{{out}}
<pre>
Line 307:
=={{header|C}}==
<
{
int r, rand_max = RAND_MAX - (RAND_MAX % 5);
Line 326:
printf(check(rand7, 7, 1000000, .05) ? "flat\n" : "not flat\n");
return 0;
}</
{{out}}
<pre>
Line 335:
=={{header|C sharp}}==
{{trans|Java}}
<
using System;
Line 361:
return 1 + random.Next(5);
}
}</
=={{header|C++}}==
This solution tries to minimize calls to the underlying d5 by reusing information from earlier calls.
<
{
public:
Line 413:
test_distribution(d5, 1000000, 0.001);
test_distribution(d7, 1000000, 0.001);
}</
=={{header|Clojure}}==
Uses the verify function defined in [[Verify distribution uniformity/Naive#Clojure]]
<
(defn dice7 []
Line 431:
(doseq [n [100 1000 10000] [num count okay?] (verify dice7 n)]
(println "Saw" num count "times:"
(if okay? "that's" " not") "acceptable"))</
<pre>Saw 0 10 times: not acceptable
Line 457:
=={{header|Common Lisp}}==
{{trans|C}}
<
(1+ (random 5)))
Line 463:
(loop for d55 = (+ (* 5 (d5)) (d5) -6)
until (< d55 21)
finally (return (1+ (mod d55 7)))))</
<pre>> (check-distribution 'd7 1000)
Line 479:
=={{header|D}}==
{{trans|C++}}
<
import verify_distribution_uniformity_naive: distCheck;
Line 525:
distCheck(&fiveToSevenNaive, N, 1);
distCheck(&fiveToSevenSmart, N, 1);
}</
{{out}}
<pre>1 80365
Line 552:
{{trans|Common Lisp}}
{{improve|E|Write dice7 in a prettier fashion and use the distribution checker once it's been written.}}
<
return entropy.nextInt(5) + 1
}
Line 560:
while ((d55 := 5 * dice5() + dice5() - 6) >= 21) {}
return d55 %% 7 + 1
}</
<
for x in 1..1000 {
bins[dice7() - 1] += 1
}
println(bins.snapshot())</
=={{header|Elixir}}==
<
def dice5, do: :rand.uniform( 5 )
Line 585:
IO.inspect VerifyDistribution.naive( fun5, 1000000, 3 )
fun7 = fn -> Dice.dice7 end
IO.inspect VerifyDistribution.naive( fun7, 1000000, 3 )</
{{out}}
Line 594:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module( dice ).
Line 611:
dice7_small_enough( N ) when N < 21 -> N div 3 + 1;
dice7_small_enough( _N ) -> dice7().
</syntaxhighlight>
{{out}}
Line 620:
=={{header|Factor}}==
<
math math.functions math.statistics math.vectors math.ranges ;
IN: rosetta-code.dice7
Line 676:
{ 1 10 100 1000 10000 100000 1000000 }
[| times | 0.02 7 [ dice7 ] times verify ] each
;</
{{out}}
Line 697:
=={{header|Forth}}==
{{works with|GNU Forth}}
<
: d5 5 random 1+ ;
Line 703:
: d7
begin d5 d5 2dup discard? while 2drop repeat
1- 5 * + 1- 7 mod 1+ ;</
{{out}}
<pre>cr ' d7 1000000 7 1 check-distribution .
Line 718:
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
implicit none
Line 754:
call distcheck(rand7, samples, 0.001)
end program</
{{out}}
<pre>Distribution Uniform
Line 769:
=={{header|FreeBASIC}}==
{{trans|Liberty BASIC}}
<
Function dice5() As Integer
Return Int(Rnd * 5) + 1
Line 786:
If Not(distCheck(n, 0.05)) Then Print "Test failed" Else Print "Test passed"
Sleep
</syntaxhighlight>
{{out}}
<pre>
Line 793:
=={{header|Go}}==
<
import (
Line 848:
max, flatEnough = distCheck(dice7, 7, calls, 500)
fmt.Println("Max delta:", max, "Flat enough:", flatEnough)
}</
{{out}}
<pre>
Line 856:
=={{header|Groovy}}==
<
int rand5() {
Line 868:
}
(raw % 7) + 1
}</
Test:
<
(1..6). each {
def counts = [0g, 0g, 0g, 0g, 0g, 0g, 0g]
Line 895:
=============="""
test(it)
}</
{{out}}
<pre style="height:30ex;overflow:scroll;">TRIAL #1
Line 1,005:
=={{header|Haskell}}==
<
import Data.List
Line 1,013:
let d7 = 5*d51+d52-6
if d7 > 20 then sevenFrom5Dice
else return $ 1 + d7 `mod` 7</
{{out}}
<
[2,3,1,1,6,2,5,6,5,3]</
Test:
<
(1,(142759,True))
(2,(143078,True))
Line 1,025:
(5,(142896,True))
(6,(143028,True))
(7,(143130,True))</
=={{header|Icon}} and {{header|Unicon}}==
{{trans|Ruby}}
Uses <code>verify_uniform</code> from [[Simple_Random_Distribution_Checker#Icon_and_Unicon|here]].
<syntaxhighlight lang="icon">
$include "distribution-checker.icn"
Line 1,046:
else write ("skewed")
end
</syntaxhighlight>
{{out}}
Line 1,062:
=={{header|J}}==
The first step is to create 7-sided dice rolls from 5-sided dice rolls (<code>rollD5</code>):
<
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,068:
groupin3s=: [: >. >: % 3: NB. increments, divides by 3 and takes ceiling
getD7=: groupin3s@keepGood@toBase10@roll2xD5</
Here are a couple of variations on the theme that achieve the same result:
<
getD7c=: [: (#~ 7&>:) 3 >.@%~ [: 5&#.&.:<:@rollD5 ] , 2:</
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>:
<
n=. */y NB. product of vector y is total number of D7 rolls required
rolls=. '' NB. initialize empty noun rolls
Line 1,082:
end.
y $ rolls NB. shape the result according to the vector y
)</
Here's a tacit definition that does the same thing:
<
accumD7Rolls=: ] , getD7@getNumRolls NB. accumulates getD7 rolls
isNotEnough=: */@[ > #@] NB. checks if enough D7 rolls accumulated
rollD7t=: ] $ (accumD7Rolls ^: isNotEnough ^:_)&''</
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:
<
6 4 5 1 4 2 4 5 2 5
rollD7t 2 5 NB. 2 by 5 array of D7 rolls
Line 1,110:
1
($@rollD7x -: $@rollD7t) 2 3 5
1</
=={{header|Java}}==
{{trans|Python}}
<
public class SevenSidedDice
{
Line 1,134:
return 1+rnd.nextInt(5);
}
}</
=={{header|JavaScript}}==
{{trans|Ruby}}
<
{
return 1 + Math.floor(5 * Math.random());
Line 1,155:
distcheck(dice5, 1000000);
print();
distcheck(dice7, 1000000);</
{{out}}
<pre>1 199792
Line 1,172:
=={{header|Julia}}==
<
function dice7()
r = 5*dice5() + dice5() - 6
r < 21 ? (r%7 + 1) : dice7()
end</
Distribution check:
<pre>julia> hist([dice5() for i=1:10^6])
Line 1,186:
=={{header|Kotlin}}==
<
import java.util.Random
Line 1,229:
fun main(args: Array<String>) {
checkDist(::dice7, 1_400_000)
}</
Sample output:
Line 1,249:
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
n=1000000 '1000000 would take several minutes
print "Testing ";n;" times"
Line 1,273:
dice5=1+int(rnd(0)*5) '1..5: dice5
end function
</syntaxhighlight>
{{Out}}
<pre>
Line 1,291:
=={{header|Lua}}==
<
function dice7()
Line 1,297:
if x > 20 then return dice7() end
return x%7 + 1
end</
=={{header|M2000 Interpreter}}==
Line 1,303:
We check for uniform numbers using +-5% from expected value.
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Def long i, calls, max, min
Line 1,339:
}
CheckIt
</syntaxhighlight>
{{out}}
Line 1,366:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
If [tmp$ < 21, 1 + Mod[tmp$ , 7], sevenFrom5Dice])</
<pre>CheckDistribution[sevenFrom5Dice, 1000000, 5]
->Expected: 142857., Generated :{142206,142590,142650,142693,142730,143475,143656}
Line 1,374:
=={{header|Nim}}==
We use the distribution checker from task [[Simple Random Distribution Checker#Nim|Simple Random Distribution Checker]].
<
Line 1,409:
import random
randomize()
checkDist(dice7, 1_000_000, 0.5)</
{{out}}
Line 1,417:
=={{header|OCaml}}==
<
let dice7 =
Line 1,433:
in
aux
;;</
=={{header|PARI/GP}}==
<
dice7()={
Line 1,442:
while((t=dice5()*5+dice5()) > 21,);
(t+2)\3
};</
=={{header|Pascal}}==
Line 1,450:
A chi-squared test can be carried out with the help of statistical tables, and is preferred here to an arbitrary "naive" test.
<
unit UConverter;
(*
Line 1,589:
until false;
end.
</syntaxhighlight>
{{out}}
<pre>
Line 1,607:
=={{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.
<
sub dice7 {
Line 1,620:
$count7{dice7()}++ for 1..$n;
printf "%s: %5.2f%%\n", $_, 100*($count7{$_}/$n*7-1) for sort keys %count7;
</syntaxhighlight>
{{out}}
<pre>
Line 1,634:
=={{header|Phix}}==
replace rand7() in [[Verify_distribution_uniformity/Naive#Phix]] with:
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">dice5</span><span style="color: #0000FF;">()</span>
<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>
Line 1,645:
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</
{{out}}
<pre>
Line 1,652:
=={{header|PicoLisp}}==
<
(rand 1 5) )
Line 1,658:
(use R
(until (> 21 (setq R (+ (* 5 (dice5)) (dice5) -6))))
(inc (% R 7)) ) )</
{{out}}
<pre>: (let R NIL
Line 1,667:
=={{header|PureBasic}}==
{{trans|Lua}}
<
ProcedureReturn Random(4) + 1
EndProcedure
Line 1,680:
ProcedureReturn x % 7 + 1
EndProcedure</
=={{header|Python}}==
<
def dice5():
Line 1,690:
def dice7():
r = dice5() + dice5() * 5 - 6
return (r % 7) + 1 if r < 21 else dice7()</
Distribution check using [[Simple Random Distribution Checker#Python|Simple Random Distribution Checker]]:
<pre>>>> distcheck(dice5, 1000000, 1)
Line 1,699:
=={{header|Quackery}}==
<
[ dice5 5 *
Line 1,710:
6 6 7 7 7 ]
dup 0 = iff
drop again ] is dice7 ( --> n )</
{{out}}
Line 1,724:
=={{header|R}}==
5-sided die.
<
Simple but slow 7-sided die, using a while loop.
<
{
score <- numeric()
Line 1,736:
score
}
system.time(dice7.while(1e6)) # longer than 4 minutes</
More complex, but much faster vectorised version.
<
{
morethan2n <- 3 * n + 10 + (n %% 2) #need more than 2*n samples, because some are discarded
Line 1,755:
} else score
}
system.time(dice7.vec(1e6)) # ~1 sec</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(define (dice5) (add1 (random 5)))
Line 1,765:
(define res (+ (* 5 (dice5)) (dice5) -6))
(if (< res 21) (+ 1 (modulo res 7)) (dice7)))
</syntaxhighlight>
Checking the uniformity using math library:
<
-> (require math/statistics)
-> (samples->hash (for/list ([i 700000]) (dice7)))
Line 1,779:
(2 . 99927)
(1 . 99622))
</syntaxhighlight>
=={{header|Raku}}==
Line 1,785:
{{works with|Rakudo|2018.03}}
<syntaxhighlight lang="raku"
sub d5() { $d5.roll; } # 1d5
Line 1,804:
for @dist.kv -> $i, $v {
say "$i\t$v\t" ~ (($v - $expect)/$expect*100).fmt("%+.2f%%") if $v;
}</
{{out}}
<pre>Expect 142857.143
Line 1,817:
=={{header|REXX}}==
<
parse arg trials sample seed . /*obtain optional arguments from the CL*/
if trials=='' | trials="," then trials= 1 /*Not specified? Then use the default.*/
Line 1,838:
' difference from expected:'right(die.j - expect, length(sample) )
end /*j*/
end /*#*/ /*stick a fork in it, we're all done. */</
{{out|output|text= when using the input of: <tt> 11 </tt>}}
Line 1,945:
=={{header|Ring}}==
<
# Project : Seven-sided dice from five-sided dice
Line 1,965:
rnd = random(4) + 1
return rnd
</syntaxhighlight>
Output:
<pre>
Line 1,974:
{{trans|Tcl}}
Uses <code>distcheck</code> from [[Simple_Random_Distribution_Checker#Ruby|here]].
<
def d5
Line 1,988:
distcheck(1_000_000) {d5}
distcheck(1_000_000) {d7}</
{{out}}
Line 2,006:
=={{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)].
<
object SevenSidedDice extends App {
Line 2,022:
println("Random number from 1 to 7: " + seven)
}</
=={{header|Sidef}}==
{{trans|Perl}}
<
func dice7 {
Line 2,041:
count7.keys.sort.each { |k|
printf("%s: %5.2f%%\n", k, 100*(count7{k}/n * 7 - 1));
}</
{{out}}
<pre>1: -0.00%
Line 2,053:
=={{header|Tcl}}==
Any old D&D hand will know these as a D5 and a D7...
<
proc D7 {} {
Line 2,062:
}
}
}</
Checking:
<span class="sy0">%</span> distcheck D5 <span class="nu0">1000000</span>
Line 2,071:
=={{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.
<
'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
Line 2,112:
Next i
Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(Bins, 0.05); """"
End Sub</
{{out}}<pre>[1] "Data set:" 142418 142898 142940 142573 143030 143139 143002
Chi-squared test for given frequencies
Line 2,120:
=={{header|VBScript}}==
<
function dice5
Line 2,132:
loop until j < 21
dice7 = j mod 7 + 1
end function</
=={{header|Verilog}}==
<
///////////////////////////////////////////////////////////////////////////////
Line 2,259:
end
endmodule
</syntaxhighlight>
Compiling with Icarus Verilog
Line 2,287:
{{libheader|Wren-sort}}
{{libheader|Wren-fmt}}
<
import "/sort" for Sort
import "/fmt" for Fmt
Line 2,329:
}
checkDist.call(dice7, 1400000, 0.5)</
{{out}}
Line 2,349:
=={{header|zkl}}==
<
fcn die7{ while((r:=5*die5() + die5())>=27){} r/3-1 }
Line 2,360:
println("Looking for ",100.0/7,"%");
rtest(0d1_000_000);</
{{out}}
<pre>
|