One of n lines in a file: Difference between revisions
Content added Content deleted
m (Add reference to Rust rand library) |
(Added Kotlin) |
||
Line 1,114: | Line 1,114: | ||
9 => 100139 |
9 => 100139 |
||
10 => 99778 |
10 => 99778 |
||
</pre> |
|||
=={{header|Kotlin}}== |
|||
<lang scala>// version 1.1.51 |
|||
import java.util.Random |
|||
val r = Random() |
|||
fun oneOfN(n: Int): Int { |
|||
var choice = 1 |
|||
for (i in 2..n) { |
|||
if (r.nextDouble() < 1.0 / i) choice = i |
|||
} |
|||
return choice |
|||
} |
|||
fun main(args: Array<String>) { |
|||
val n = 10 |
|||
val freqs = IntArray(n) |
|||
val reps = 1_000_000 |
|||
repeat(reps) { |
|||
val num = oneOfN(n) |
|||
freqs[num - 1]++ |
|||
} |
|||
for (i in 1..n) println("Line ${"%-2d".format(i)} = ${freqs[i - 1]}") |
|||
}</lang> |
|||
Sample output: |
|||
<pre> |
|||
Line 1 = 100363 |
|||
Line 2 = 99669 |
|||
Line 3 = 100247 |
|||
Line 4 = 100248 |
|||
Line 5 = 100401 |
|||
Line 6 = 99457 |
|||
Line 7 = 100015 |
|||
Line 8 = 100215 |
|||
Line 9 = 99920 |
|||
Line 10 = 99465 |
|||
</pre> |
</pre> |
||