RosettaCodeData/Task/Knuths-algorithm-S/Kotlin/knuths-algorithm-s-1.kotlin

29 lines
601 B
Text
Raw Permalink Normal View History

2018-08-17 15:15:24 +01:00
// version 1.2.51
2017-09-23 10:01:46 +02:00
import java.util.Random
2018-08-17 15:15:24 +01:00
val rand = Random()
2017-09-23 10:01:46 +02:00
class SOfN<T>(val n: Int) {
private val sample = ArrayList<T>(n)
private var i = 0
2018-08-17 15:15:24 +01:00
fun process(item: T): List<T> {
2017-09-23 10:01:46 +02:00
if (++i <= n)
sample.add(item)
else if (rand.nextInt(i) < n)
sample[rand.nextInt(n)] = item
return sample
}
}
fun main(args: Array<String>) {
val bin = IntArray(10)
(1..100_000).forEach {
val sOfn = SOfN<Int>(3)
2018-08-17 15:15:24 +01:00
for (d in 0..8) sOfn.process(d)
for (s in sOfn.process(9)) bin[s]++
2017-09-23 10:01:46 +02:00
}
println(bin.contentToString())
}