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

Added Kotlin
m (→‎{{header|REXX}}: made some improvements.)
(Added Kotlin)
Line 1,130:
julia> hist([dice7() for i=1:10^6])
(0:1:7,[142390,143032,142837,142999,142800,142642,143300])</pre>
 
=={{header|Kotlin}}==
<lang scala>// version 1.1.3
 
import java.util.Random
 
val r = Random()
 
fun dice5() = 1 + r.nextInt(5)
 
fun dice7(): Int {
while (true) {
val t = (dice5() - 1) * 5 + dice5() - 1
if (t >= 21) continue
return 1 + t / 3
}
}
 
fun checkDist(gen: () -> Int, nRepeats: Int, tolerance: Double = 0.5) {
val occurs = mutableMapOf<Int, Int>()
for (i in 1..nRepeats) {
val d = gen()
if (occurs.containsKey(d))
occurs[d] = occurs[d]!! + 1
else
occurs.put(d, 1)
}
val expected = (nRepeats.toDouble()/ occurs.size).toInt()
val maxError = (expected * tolerance / 100.0).toInt()
println("Repetitions = $nRepeats, Expected = $expected")
println("Tolerance = $tolerance%, Max Error = $maxError\n")
println("Integer Occurrences Error Acceptable")
val f = " %d %5d %5d %s"
var allAcceptable = true
for ((k,v) in occurs.toSortedMap()) {
val error = Math.abs(v - expected)
val acceptable = if (error <= maxError) "Yes" else "No"
if (acceptable == "No") allAcceptable = false
println(f.format(k, v, error, acceptable))
}
println("\nAcceptable overall: ${if (allAcceptable) "Yes" else "No"}")
}
 
fun main(args: Array<String>) {
checkDist(::dice7, 1_400_000)
}</lang>
 
Sample output:
<pre>
Repetitions = 1400000, Expected = 200000
Tolerance = 0.5%, Max Error = 1000
 
Integer Occurrences Error Acceptable
1 199285 715 Yes
2 200247 247 Yes
3 199709 291 Yes
4 199983 17 Yes
5 199990 10 Yes
6 200664 664 Yes
7 200122 122 Yes
 
Acceptable overall: Yes
</pre>
 
=={{header|Liberty BASIC}}==
9,476

edits