Skip to content

Instantly share code, notes, and snippets.

@reckenrode
Created March 26, 2019 23:56
Show Gist options
  • Save reckenrode/b7451686a884d6ec62a700676d6d76c0 to your computer and use it in GitHub Desktop.
Save reckenrode/b7451686a884d6ec62a700676d6d76c0 to your computer and use it in GitHub Desktop.
use rand::{Rng, thread_rng};
use std::{
collections::HashMap,
io::Write,
thread
};
fn encounters_per_week<R: Rng>(rng: &mut R) -> u32 {
let mut count = 0;
for _ in 1..=(7*6) {
if rng.gen_range(1, 8) == 1 {
count += 1;
}
}
count
}
fn calculate_distribution() -> HashMap<u32, u32> {
let mut rng = thread_rng();
let mut distribution: HashMap<u32, u32> = HashMap::new();
for _ in 1..=5_000_000 {
let encounters = encounters_per_week(&mut rng);
if let Some(times) = distribution.get(&encounters) {
distribution.insert(encounters, times + 1);
} else {
distribution.insert(encounters, 1);
}
}
distribution
}
fn main() {
print!("Running Monte Carlo sim on the adventuring week…");
std::io::stdout().flush().expect("stdout flushed");
let handle1 = thread::spawn(calculate_distribution);
let handle2 = thread::spawn(calculate_distribution);
let handle3 = thread::spawn(calculate_distribution);
let handle4 = thread::spawn(calculate_distribution);
let handle5 = thread::spawn(calculate_distribution);
let handle6 = thread::spawn(calculate_distribution);
let handle7 = thread::spawn(calculate_distribution);
let handle8 = thread::spawn(calculate_distribution);
let distributions = [
handle1.join().expect("joined"),
handle2.join().expect("joined"),
handle3.join().expect("joined"),
handle4.join().expect("joined"),
handle5.join().expect("joined"),
handle6.join().expect("joined"),
handle7.join().expect("joined"),
handle8.join().expect("joined")
];
let distribution: HashMap<u32, u32> = HashMap::new();
let distribution = distributions.iter().fold(distribution, |acc, x| {
let mut acc = acc;
for key in x.keys() {
acc.insert(*key, acc.get(key).unwrap_or(&0) + x[key]);
}
acc
});
println!("done");
let keys = {
let mut keys: Vec<&u32> = distribution.keys().collect();
keys.sort();
keys
};
for key in keys {
let key_f = distribution[key] as f64;
println!("# encounters: {} @ {}%", key, key_f / 400_000f64)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment