Skip to content

Instantly share code, notes, and snippets.

@outfrost
Last active June 19, 2023 14:05
Show Gist options
  • Save outfrost/f9f2fce037eab0b313b94de2fc2e87f1 to your computer and use it in GitHub Desktop.
Save outfrost/f9f2fce037eab0b313b94de2fc2e87f1 to your computer and use it in GitHub Desktop.
Procedural illustration of the Monty Hall problem
use rand::{thread_rng, Rng};
const DOORS: u32 = 3;
const ROUNDS: u32 = 1000000;
const SWITCH: bool = true;
fn main() {
if DOORS < 3 {
panic!("Doesn't work for fewer than 3 doors.");
}
println!(
"{} doors, {} rounds, {} player",
DOORS,
ROUNDS,
if SWITCH { "switching" } else { "non-switching" }
);
let mut wins = 0;
for _ in 0..ROUNDS {
// host picks the winning door
let winning = thread_rng().gen_range(0..DOORS);
// player guesses
let guess = thread_rng().gen_range(0..DOORS);
// host opens DOORS-2 non-winning doors;
// the player's guess and the winning door remain closed
let mut other_closed = winning;
// if player happened to guess correctly, a different random door will stay closed
while other_closed == guess {
other_closed = thread_rng().gen_range(0..DOORS);
}
// 2 doors always stay closed;
// at this point, `guess` and `other_closed` contain 2 distinct numbers
// player either switches to the other closed door, or sticks with their guess
let final_choice = if SWITCH { other_closed } else { guess };
if final_choice == winning {
wins += 1;
}
}
println!(
"{} wins -- {}% win rate",
wins,
(100.0 * (wins as f32) / (ROUNDS as f32)).round() as i32
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment