Scala
Saya tahu pengguna saya akan skeptis, jadi saya telah menyertakan bukti bahwa keacakan saya benar-benar adil!
object DrinkChooser {
def main(args: Array[String]): Unit = {
proveRandomness()
val names = List("John","Jeff","Emma","Steve","Julie")
val buyer = names(randomChoice(names.size))
println(s"$buyer will buy the drinks this time!")
}
def proveRandomness(): Unit = {
val trials = 10000
val n = 4
val choices = for (_ <- 1 to 10000) yield randomChoice(n)
(choices groupBy(identity)).toList.sortBy(_._1) foreach { case (a, x) =>
println(a + " chosen " + (x.size * 100.0 / trials) + "%")
}
}
def randomChoice(n: Int): Int = {
var x = 1
for (i <- 1 to 1000) { // don't trust random, add in more randomness!
x = (x * randomInt(1, n)) % (n + 1)
}
x
}
// random int between min and max inclusive
def randomInt(min: Int, max: Int) = {
new scala.util.Random().nextInt(max - min + 1) + min
}
}
Satu contoh dijalankan:
1 chosen 25.31%
2 chosen 24.46%
3 chosen 24.83%
4 chosen 25.4%
John will buy the drinks this time!
Kecuali orang lain sangat beruntung, John akan selalu membeli minuman.
"Bukti" keacakan bergantung pada fakta yang rand(1, 4) * rand(1, 4) % 5
masih merata antara 1 dan 4, inklusif. Tapi rand(1, 5) * rand(1, 5) % 6
merosot. Ada kemungkinan Anda mendapatkan 0, yang kemudian akan membuat hasil akhir 0 terlepas dari sisa "keacakan".