Skip to content

Instantly share code, notes, and snippets.

@aaronjeline
Created December 25, 2020 22:31
Show Gist options
  • Save aaronjeline/7b6e403f74c4c78d8ace52ac00c10a5f to your computer and use it in GitHub Desktop.
Save aaronjeline/7b6e403f74c4c78d8ace52ac00c10a5f to your computer and use it in GitHub Desktop.
Van Neuman Extractor
use std::fs::File;
use std::io::Read;
use std::mem::{transmute, size_of};
fn get_rand_int() -> u32 {
let mut b = [0;4];
let mut f = File::open("/dev/random").expect("Coulnd't open");
f.read(&mut b).expect("Coulnd't read");
unsafe { transmute(b) }
}
fn flip_coin() -> bool {
let b = get_rand_int();
(b % 8) == 0
}
fn extractor() -> bool {
let mut output = false;
loop {
let a = flip_coin();
let b = flip_coin();
if a == b {
continue;
} else {
output = a;
break;
}
}
output
}
fn run_expirement<T>(count : usize, f : T) -> f64
where T : Fn() -> bool {
let mut heads = 0.0;
for _ in 0..count {
if f() { heads += 1.0; }
}
heads / (count as f64)
}
fn main() -> () {
let args : Vec<_> = std::env::args().collect();
let count : usize = args[1].parse().expect("Malformed args");
let p1 = run_expirement(count, flip_coin);
println!("Initial p = {}", p1);
let p2 = run_expirement(count, extractor);
println!("Extracted p = {}", p2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment