Skip to content

Instantly share code, notes, and snippets.

@darkwater
Last active May 16, 2017 07:46
Show Gist options
  • Save darkwater/4a3ea7e79c9deb178c89d3fff9d57c88 to your computer and use it in GitHub Desktop.
Save darkwater/4a3ea7e79c9deb178c89d3fff9d57c88 to your computer and use it in GitHub Desktop.
Simulates the Monty Hall problem
// Run with two arguments: strategy and simulations
//
// eg.
// cargo run stay 500
// cargo run switch 10000
extern crate rand;
use rand::Rng;
use std::env;
#[derive(Debug)]
enum Strategy {
Stay,
Switch,
}
fn main() {
let arguments: Vec<String> = env::args().skip(1).take(2).collect();
let strategy = match &*arguments[0] {
"stay" => Strategy::Stay,
"switch" => Strategy::Switch,
arg => panic!("Invalid strategy {:?}", arg)
};
let simulations = arguments[1].parse::<i32>().unwrap();
let mut wins = 0;
let mut games = 0;
for _ in 0..simulations {
let mut rng = rand::thread_rng();
let prize_slot = rng.gen_range::<i32>(0, 3);
let first_choice = rng.gen_range::<i32>(0, 3);
let second_choice;
let revealed = match prize_slot {
0 => match first_choice {
0 => rng.gen_range::<i32>(1, 3),
1 => 2,
2 => 1,
_ => unreachable!()
},
1 => match first_choice {
0 => 2,
1 => rng.gen_range::<i32>(0, 2) * 2, // 0 or 1 times 2
2 => 0,
_ => unreachable!()
},
2 => match first_choice {
0 => 1,
1 => 0,
2 => rng.gen_range::<i32>(0, 2),
_ => unreachable!()
},
_ => unreachable!()
};
let left_over = 3 - first_choice - revealed;
assert_ne!(revealed, first_choice);
assert_ne!(revealed, prize_slot);
assert_ne!(left_over, first_choice);
assert_ne!(left_over, revealed);
match strategy {
Strategy::Stay => second_choice = first_choice,
Strategy::Switch => second_choice = left_over,
}
if second_choice == prize_slot {
wins += 1;
}
games += 1;
}
println!("Results:");
println!(" Wins: {}", wins);
println!(" Total games: {}", games);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment