One of n lines in a file: Difference between revisions

Add rust solution
(Add rust solution)
Line 1,752:
9 100520
10 100592</pre>
 
=={{header|Rust}}==
<lang rust>
extern crate rand;
 
use rand::Rng;
 
fn one_of_n(rng: &mut rand::ThreadRng, n: usize) -> usize {
(1..n).fold(0, |keep, cand|
match rng.next_f64() {
y if y < (1.0 / (cand + 1) as f64) => cand,
_ => keep
}
)
}
 
fn main() {
let mut dist = [0usize; 10];
let mut rng = rand::thread_rng();
 
for _ in 0..1_000_000 {
dist[one_of_n(&mut rng, 10)] += 1;
}
 
println!("{:?}", dist);
}
</lang>
{{out}}
<pre>
[100203, 100012, 99854, 99686, 99888, 99899, 99559, 100584, 100208, 100107]
</pre>
 
=={{header|Scala}}==
<lang Scala>def one_of_n(n: Int, i: Int = 1, j: Int = 1): Int =
Anonymous user