One of n lines in a file: Difference between revisions

Content added Content deleted
Line 1,916: Line 1,916:
fn one_of_n<R: Rng>(rng: &mut R, n: usize) -> usize {
fn one_of_n<R: Rng>(rng: &mut R, n: usize) -> usize {
(1..n).fold(0, |keep, cand|
(1..n).fold(0, |keep, cand|
match rng.next_f64() {
if rng.next_f64() < (1.0 / (cand + 1) as f64) {
y if y < (1.0 / (cand + 1) as f64) => cand,
cand
_ => keep
} else {
keep
}
}
)
)
Line 1,924: Line 1,925:


fn main() {
fn main() {
let mut dist = [0_usize; 10];
const LINES: usize = 10;

let mut dist = [0; LINES];
let mut rng = thread_rng();
let mut rng = thread_rng();


for _ in 0..1_000_000 {
for _ in 0..1_000_000 {
let num = one_of_n(&mut rng, 10);
let num = one_of_n(&mut rng, LINES);
dist[num] += 1;
dist[num] += 1;
}
}