Created
August 16, 2024 09:07
-
-
Save arialdomartini/c9ea70998602ede8b3c2dd4108791423 to your computer and use it in GitHub Desktop.
random fizz buzz
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::fs::OpenOptions; | |
use std::io::Write; | |
use rand::{Rng, SeedableRng}; | |
use rand_pcg::Pcg64; | |
fn fizz_buzz() -> impl Iterator<Item = String> { | |
(1..).map(|i| { | |
if i % 15 == 0 { | |
"fizzbuzz".to_string() | |
} else if i % 3 == 0 { | |
"fizz".to_string() | |
} else if i % 5 == 0 { | |
"buzz".to_string() | |
} else { | |
i.to_string() | |
} | |
}) | |
} | |
fn random_fizz_buzz(seed: u64) -> impl Iterator<Item = String> { | |
let mut rng = Pcg64::seed_from_u64(seed); | |
let choices = ["fizz", "buzz", "fizzbuzz"]; | |
(1..).map(move |i| { | |
let choice = rng.gen_range(0..4); | |
if choice == 3 { | |
i.to_string() | |
} else { | |
choices[choice].to_string() | |
} | |
}) | |
} | |
fn match_up_to<T: PartialEq>(reference: impl Iterator<Item = T>, xs: impl Iterator<Item = T>) -> usize { | |
reference.zip(xs).take_while(|(r, x)| r == x).count() | |
} | |
fn brute_force() { | |
let report_file = "report.txt"; | |
std::fs::remove_file(report_file).unwrap_or(()); | |
let mut max_so_far = 0; | |
for seed in 0u64.. { | |
let real_fizz_buzz = fizz_buzz(); | |
let generated = random_fizz_buzz(seed); | |
let up_to = match_up_to(real_fizz_buzz, generated); | |
if up_to > max_so_far { | |
let mut file = OpenOptions::new() | |
.create(true) | |
.append(true) | |
.open(report_file) | |
.unwrap(); | |
writeln!(file, "{} => {}", seed, up_to).unwrap(); | |
max_so_far = up_to; | |
} | |
} | |
} | |
fn print_fizz_buzz() -> impl Iterator<Item = String> { | |
let mut rng = Pcg64::seed_from_u64(5535459); | |
(1..).map(move |i| { ["fizz", "buzz","fizzbuzz", &i.to_string()][rng.gen_range(0..4)].to_string() }) | |
} | |
fn main() { | |
//print_fizz_buzz().take(20).for_each(|i| println!("{}", i)); | |
brute_force() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment