Created
November 1, 2022 09:40
-
-
Save Andrej123456789/674eec9a91a23af4a5ef125ddeaf3385 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 std::time::Instant; | |
use rand::thread_rng; | |
use rand::seq::SliceRandom; | |
fn create_shuffled_numbers(num_prisoners: i64) -> Vec<i64> { | |
let mut a: Vec<i64> = Vec::new(); | |
let mut i = 0; | |
while i < num_prisoners { | |
a.push(i); | |
i += 1 | |
} | |
a.shuffle(&mut thread_rng()); | |
return a; | |
} | |
fn single_prisoner_attempt(prisoner_number: i64, boxes: &mut Vec<i64>) -> bool { | |
let mut box_to_open = prisoner_number; | |
let mut i = 0; | |
while i < boxes.len() / 2 { | |
if prisoner_number == boxes[box_to_open as usize] { | |
return true | |
} | |
box_to_open = boxes[box_to_open as usize]; | |
i += 1; | |
} | |
return false | |
} | |
fn run_simulation(num_prisoners: i64) -> bool { | |
let mut boxes = create_shuffled_numbers(num_prisoners); | |
let mut i = 0; | |
while i < num_prisoners { | |
if single_prisoner_attempt(i, &mut boxes) == false { | |
return false; | |
} | |
i += 1; | |
} | |
return true; | |
} | |
fn single(prisoners: i64, iterations: i64) { | |
let (mut successes, mut num_total_simulations) = (0, 0); | |
let mut i = 0; | |
while i < iterations { | |
if run_simulation(prisoners) == true { | |
successes += 1; | |
} | |
num_total_simulations += 1; | |
println!( | |
"[{} prisoners] Successful simulations: {} out of {} {:.2} {:.4}", | |
prisoners, | |
successes, | |
num_total_simulations, | |
num_total_simulations as f32 / successes as f32, | |
100.0 * successes as f32 / num_total_simulations as f32 | |
); | |
i += 1; | |
} | |
} | |
fn main() { | |
let now = Instant::now(); | |
single(10, 1000000); | |
let elapsed = now.elapsed(); | |
println!("Elapsed: {:.2?}", elapsed); | |
} | |
/* | |
Create new cargo project, put rand crate in Cargo.toml, put this code in main.rs and run in release mode because it is faster | |
Based on DataTime's video | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment