Skip to content

Instantly share code, notes, and snippets.

@ElectricCoffee
Created June 9, 2018 13:05
Show Gist options
  • Save ElectricCoffee/abc1158a7c0d7a617a1393ac5acfab17 to your computer and use it in GitHub Desktop.
Save ElectricCoffee/abc1158a7c0d7a617a1393ac5acfab17 to your computer and use it in GitHub Desktop.
extern crate rand;
use rand::Rng;
use std::env;
const MAX_DAYS: usize = 365;
/// Creates an array with `count` number of birthdays in it represented by numbers
/// if more than one birthday occurs on the same day, then that day's entry will be > 1
fn paradox(count: u16) -> [u16; MAX_DAYS] {
let mut arr = [0; MAX_DAYS];
let mut rng = rand::thread_rng();
for _ in 0 .. count {
let index = rng.gen_range(0, MAX_DAYS);
arr[index] += 1;
}
arr
}
/// Calculates the percentage based on a number of occurrences (hits) and the total number of trials
fn pct_u32(hits: u32, total: u32) -> f32 {
hits as f32 / total as f32 * 100.0
}
fn run(count: u16, trials: u32) {
let mut hits = 0;
println!("Running {} trials with {} random birthdays, this might take a while.", trials, count);
for t in 1 ..= trials {
if t % 100 == 0 {
let percentage = pct_u32(t, trials);
print!("\rThe trials are {:3.2}% done.", percentage);
}
for count in paradox(count).iter() {
if *count > 1 {
hits += 1;
break;
}
}
}
println!("\nThe chance of {} people having the same birthday is {:.2}% ({} trials)",
count,
pct_u32(hits, trials),
trials
);
}
fn main() {
let args: Vec<String> = env::args().collect();
let count = args.get(1);
if let Some(count) = count {
match count.parse::<u16>() {
Ok(count) => run(count, 2_000_000), // 2 million trials by default
Err(err) => println!("{}", err),
};
} else {
println!("Please supply a number as an input value")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment