Skip to content

Instantly share code, notes, and snippets.

@agaskell
Created September 13, 2024 02:24
Show Gist options
  • Select an option

  • Save agaskell/0e86312a4704b915ca45f33d4b3acea1 to your computer and use it in GitHub Desktop.

Select an option

Save agaskell/0e86312a4704b915ca45f33d4b3acea1 to your computer and use it in GitHub Desktop.
Coinflippers any
use rand::Rng;
fn flip_coin() -> Vec<bool> {
let mut rng = rand::thread_rng();
let mut results = Vec::new();
// Simulate 100 coin flips and store the boolean result
for _ in 0..100 {
let coin_flip = rng.gen_bool(0.5); // true for "Heads", false for "Tails"
results.push(coin_flip);
}
results
}
fn linear_search(results: &[bool]) -> usize {
let mut moves = 0;
let mut heads_count = 0;
// Linear search: iterate through all indexes and count moves
for i in 0..results.len() {
moves += 1;
if results[i] {
heads_count += 1;
}
if heads_count == 2 {
return moves;
}
}
moves
}
fn even_then_odd_search(results: &[bool]) -> usize {
let mut moves = 0;
let mut heads_count = 0;
// First, check even indexes
for i in (0..results.len()).step_by(2) {
moves += 1;
if results[i] {
heads_count += 1;
}
if heads_count == 2 {
return moves;
}
}
// Then, check odd indexes
for i in (1..results.len()).step_by(2) {
moves += 1;
if results[i] {
heads_count += 1;
}
if heads_count == 2 {
return moves;
}
}
moves
}
fn main() {
const ITERATIONS: usize = 1_000_000;
let mut total_moves_linear = 0;
let mut total_moves_even_odd = 0;
// Run a million iterations of each search
for _ in 0..ITERATIONS {
let results = flip_coin();
// Linear search
total_moves_linear += linear_search(&results);
// Even-then-odd search
total_moves_even_odd += even_then_odd_search(&results);
}
// Calculate average moves for each method
let avg_moves_linear = total_moves_linear as f64 / ITERATIONS as f64;
let avg_moves_even_odd = total_moves_even_odd as f64 / ITERATIONS as f64;
// Print the results
println!("After {} iterations:", ITERATIONS);
println!("Average moves (Linear Search): {:.2}", avg_moves_linear);
println!("Average moves (Even-Then-Odd Search): {:.2}", avg_moves_even_odd);
if avg_moves_linear < avg_moves_even_odd {
println!("Linear Search was more efficient!");
} else {
println!("Even-Then-Odd Search was more efficient!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment