From 3ec662bbb1477be34fb14877fa4a549a6bb4bbf7 Mon Sep 17 00:00:00 2001 From: Mike Vink Date: Thu, 14 Dec 2023 22:32:34 +0100 Subject: add day2 --- src/bin/day2.rs | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 src/bin/day2.rs (limited to 'src/bin') diff --git a/src/bin/day2.rs b/src/bin/day2.rs new file mode 100644 index 0000000..a007159 --- /dev/null +++ b/src/bin/day2.rs @@ -0,0 +1,78 @@ +#![feature(test)] +use std::error::Error; + +const COLORS: [&str; 3] = ["red", "green", "blue"]; +const AMOUNT: [u32; 3] = [12, 13, 14]; + +// NOTE: probably should just panic, filter_mapping doesn't make much sense if you need the input to be correct. +fn main() -> Result<(), Box> { + let file = std::fs::read_to_string("input/2/in.txt")?; + let cube_lines: Vec<_> = file + .lines() + .enumerate() + .filter_map(|(i, line)| -> Option<(u32, Vec<(usize, u32)>)> { + let mut fields = line.split(':'); + let id: u32 = (i + 1) as u32; + let cubes = fields + .nth(1)? + .split(';') + .flat_map(|s| { + s.trim() + .split(",") + .filter_map(|game| { + let mut fields = game.trim().split(" "); + let num: u32 = fields.next()?.parse().ok()?; + let color = fields.next()?; + let c = COLORS.iter().position(|col| *col == color)?; + Some((c, num)) + }) + .collect::>() + }) + .collect(); + Some((id, cubes)) + }) + .collect(); + + let part1: u32 = cube_lines + .iter() + .filter_map(|(id, cubes)| { + if cubes.iter().all(|(color, num)| *num <= AMOUNT[*color]) { + Some(id) + } else { + None + } + }) + .sum(); + dbg!(part1); + let part2: u32 = cube_lines + .iter() + .map(|(_, cubes)| { + cubes + .into_iter() + .fold([0, 0, 0], |mut acc, (color, num)| { + if acc[*color] < *num { + acc[*color] = *num; + } + acc + }) + .into_iter() + .product::() + }) + .sum(); + dbg!(part2); + + Ok(()) +} + +extern crate test; + +#[cfg(test)] +mod tests { + use super::*; + use test::Bencher; + + #[bench] + fn other(b: &mut Bencher) { + b.iter(|| main()); + } +} -- cgit v1.2.3