lotto/src/main.rs

103 lines
2.4 KiB
Rust
Raw Normal View History

2024-05-03 13:49:33 -05:00
use anyhow::anyhow;
2024-05-03 16:43:06 -05:00
use std::fs::File;
2024-05-03 13:49:33 -05:00
use std::io::BufRead;
2024-05-03 16:43:06 -05:00
use std::{io::BufReader, time::Instant};
2024-05-03 13:06:15 -05:00
type Ticket = [u8; 5];
const NUM_ENTRIES: usize = 10_000_000;
2024-05-03 13:49:33 -05:00
fn ticket_from_str(s: &str) -> Result<Ticket, anyhow::Error> {
let mut nums = s.split(" ").take(5).map(|s| s.parse::<u8>()).into_iter();
2024-05-03 13:06:15 -05:00
2024-05-03 13:49:33 -05:00
let num1 = nums.next();
let num2 = nums.next();
let num3 = nums.next();
let num4 = nums.next();
let num5 = nums.next();
if num1.is_none() || num2.is_none() || num3.is_none() || num4.is_none() || num5.is_none() {
return Err(anyhow!("invalid lotto number"));
2024-05-03 13:06:15 -05:00
}
2024-05-03 13:49:33 -05:00
let r = [
num1.unwrap()?,
num2.unwrap()?,
num3.unwrap()?,
num4.unwrap()?,
num5.unwrap()?,
];
2024-05-03 13:54:34 -05:00
if r[0] < 1
|| r[1] < 1
|| r[2] < 1
|| r[3] < 1
|| r[4] < 1
|| r[0] > 90
|| r[1] > 90
|| r[2] > 90
|| r[3] > 90
|| r[4] > 90
{
2024-05-03 13:54:51 -05:00
return Err(anyhow!("lotto number out of bounds"));
2024-05-03 13:06:15 -05:00
}
2024-05-03 13:49:33 -05:00
Ok(r)
2024-05-03 13:06:15 -05:00
}
fn num_matches(t1: Ticket, t2: Ticket) -> usize {
let mut result = 0;
for n1 in t1 {
for n2 in t2 {
if n1 == n2 {
result += 1;
}
}
}
result
}
2024-05-03 13:49:33 -05:00
fn main() -> Result<(), anyhow::Error> {
2024-05-03 16:43:06 -05:00
let start = Instant::now();
2024-05-03 13:58:28 -05:00
println!("Parsing entries from stdin...");
2024-05-03 13:49:33 -05:00
2024-05-03 16:43:06 -05:00
let f = File::open("/mytmpfs/10m-v2.txt")?;
let reader = BufReader::new(f);
2024-05-03 13:49:33 -05:00
let mut entries = Vec::with_capacity(NUM_ENTRIES);
for line in reader.lines() {
match line {
Ok(l) => match ticket_from_str(&l) {
Ok(n) => entries.push(n),
Err(_) => {} // noop
},
Err(_) => break,
}
2024-05-03 13:06:15 -05:00
}
2024-05-03 16:43:06 -05:00
let duration = start.elapsed();
println!(
"{} entries parsed from stdin in {}ms",
entries.len(),
duration.as_millis()
);
2024-05-03 13:06:15 -05:00
2024-05-03 13:49:33 -05:00
let winning = [68, 81, 40, 34, 85];
2024-05-03 13:06:15 -05:00
2024-05-03 13:49:33 -05:00
let start = Instant::now();
println!("Counting winners... (timer started)");
2024-05-03 13:06:15 -05:00
let mut winners: [usize; 6] = [0, 0, 0, 0, 0, 0];
for n in entries {
let num_winning = num_matches(n, winning);
winners[num_winning] += 1
}
2024-05-03 13:49:33 -05:00
println!("Done counting winners (timer stopped)");
2024-05-03 13:06:15 -05:00
let duration = start.elapsed();
println!(
"Winners: {:?}\nTime Elapsed: {}ms",
2024-05-03 16:43:06 -05:00
winners.into_iter().skip(2).collect::<Vec<usize>>(),
duration.subsec_millis(),
2024-05-03 13:06:15 -05:00
);
2024-05-03 13:49:33 -05:00
Ok(())
2024-05-03 13:06:15 -05:00
}