feat: add sample(list) and sample(list, count) methods to Random class with two sampling algorithms

This commit is contained in:
Bob Nystrom
2016-02-09 15:24:45 +00:00
parent 813594b14c
commit 19d7215412
11 changed files with 248 additions and 5 deletions
+19
View File
@@ -0,0 +1,19 @@
import "random" for Random
var random = Random.new(12345)
// Should choose all elements with roughly equal probability.
var list = ["a", "b", "c"]
var histogram = {}
for (i in 1..5000) {
var sample = random.sample(list, 3)
var string = sample.toString
if (!histogram.containsKey(string)) histogram[string] = 0
histogram[string] = histogram[string] + 1
}
System.print(histogram.count) // expect: 6
for (key in histogram.keys) {
var error = (histogram[key] / (5000 / 6) - 1).abs
if (error > 0.1) System.print("!!! %(error)")
}