How to resolve the algorithm Seven-sided dice from five-sided dice step by step in the Groovy programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Seven-sided dice from five-sided dice step by step in the Groovy programming language
Table of Contents
Problem Statement
(Given an equal-probability generator of one of the integers 1 to 5 as dice5), create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random numbers, and check the distribution for at least one million calls using the function created in Simple Random Distribution Checker.
Implementation suggestion: dice7 might call dice5 twice, re-call if four of the 25 combinations are given, otherwise split the other 21 combinations into 7 groups of three, and return the group index from the rolls. (Task adapted from an answer here)
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Seven-sided dice from five-sided dice step by step in the Groovy programming language
Source code in the groovy programming language
random = new Random()
int rand5() {
random.nextInt(5) + 1
}
int rand7From5() {
def raw = 25
while (raw > 21) {
raw = 5*(rand5() - 1) + rand5()
}
(raw % 7) + 1
}
def test = {
(1..6). each {
def counts = [0g, 0g, 0g, 0g, 0g, 0g, 0g]
def target = 10g**it
def popSize = 7*target
(0..<(popSize)).each {
def i = rand7From5() - 1
counts[i] = counts[i] + 1g
}
BigDecimal stdDev = (counts.collect { it - target}.collect { it * it }.sum() / popSize) ** 0.5g
def countMap = (0..<counts.size()).inject([:]) { map, index -> map + [(index+1):counts[index]] }
println """\
counts: ${countMap}
population size: ${popSize}
std dev: ${stdDev.round(new java.math.MathContext(3))}
"""
}
}
4.times {
println """
TRIAL #${it+1}
=============="""
test(it)
}
You may also check:How to resolve the algorithm Arrays step by step in the Elena programming language
You may also check:How to resolve the algorithm Array concatenation step by step in the REXX programming language
You may also check:How to resolve the algorithm Calendar - for REAL programmers step by step in the Julia programming language
You may also check:How to resolve the algorithm Halt and catch fire step by step in the Wren programming language
You may also check:How to resolve the algorithm Chaocipher step by step in the C# programming language