Scala
I know my users will be skeptical, so I have included a proof that my randomness is truly fair!
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
}
}
One example run:
1 chosen 25.31%
2 chosen 24.46%
3 chosen 24.83%
4 chosen 25.4%
John will buy the drinks this time!
Unless someone else gets extremely lucky, John will always buy the drinks.
The "proof" of randomness relies on the fact that rand(1, 4) * rand(1, 4) % 5
is still evenly distributed between 1 and 4, inclusive. But rand(1, 5) * rand(1, 5) % 6
is degenerate. There's the possibility you get a 0, which would then make the final result 0 regardless of the rest of the "randomness".