Last active
February 5, 2025 04:26
-
-
Save davidrhodus/aa9d58bfcbcbbca52a74ffe317a110da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use rand::prelude::*; | |
use std::collections::HashSet; | |
fn main() { | |
let num_iterations = 1_000_000; | |
let mut rng = thread_rng(); | |
let mut successful_run_count = 0; | |
for _ in 0..num_iterations { // Fixed syntax here | |
if single_trial(100, &mut rng) { | |
successful_run_count += 1; | |
} | |
} | |
let result_probability = successful_run_count as f64 / num_iterations as f64; | |
println!( | |
"After {} trials, the estimated probability that the last passenger sits in their own seat is {:.6}", | |
num_iterations, | |
result_probability | |
); | |
} | |
fn single_trial(total_passengers: usize, rng: &mut impl Rng) -> bool { | |
let mut available_seats: HashSet<usize> = (0..total_passengers).collect(); | |
// First passenger chooses randomly | |
let initial_seat = *available_seats.iter().choose(rng).unwrap(); | |
available_seats.remove(&initial_seat); | |
// Process all passengers except the last one | |
for passenger in 1..(total_passengers - 1) { | |
if !available_seats.remove(&passenger) { | |
// If assigned seat is taken, choose randomly from remaining seats | |
let random_seat = *available_seats.iter().choose(rng).unwrap(); | |
available_seats.remove(&random_seat); | |
} | |
} | |
// Check if last passenger gets their assigned seat | |
*available_seats.iter().next().unwrap() == total_passengers - 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment