From bf953b798007739bb9e1f32bb691dde3d953df7e Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Sat, 2 Dec 2023 10:40:33 +0100 Subject: [PATCH] Implement 2023 day 2 part 2 --- 2023/benches/days.rs | 2 +- 2023/src/day02.rs | 46 +++++++++++++++++++++++++++++++------------- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/2023/benches/days.rs b/2023/benches/days.rs index 95533c3..d079062 100644 --- a/2023/benches/days.rs +++ b/2023/benches/days.rs @@ -9,7 +9,7 @@ use criterion::Criterion; use aoc_2023::get_implementation; /// Number of days we have an implementation to benchmark -const DAYS_IMPLEMENTED: u8 = 1; +const DAYS_IMPLEMENTED: u8 = 2; fn read_input(day: u8) -> std::io::Result> { let input_path = format!("inputs/{day:02}.txt"); diff --git a/2023/src/day02.rs b/2023/src/day02.rs index 50fb387..c9c3131 100644 --- a/2023/src/day02.rs +++ b/2023/src/day02.rs @@ -53,19 +53,10 @@ fn parse_game(i: &[u8]) -> IResult<&[u8], (u8, [u8; 3])> { )(i) } -pub fn part1(input: &[u8]) -> anyhow::Result { +fn parts_common(input: &[u8], map: impl Fn((u8, [u8; 3])) -> u32) -> anyhow::Result { let mut game_it = iterator(input, parse_game); - let total: u32 = game_it - .into_iter() - .filter_map(|(id, colors)| { - if colors[0] <= 12 && colors[1] <= 13 && colors[2] <= 14 { - Some(u32::from(id)) - } else { - None - } - }) - .sum(); + let total: u32 = game_it.into_iter().map(map).sum(); game_it.finish().map_err(|e| match e { nom::Err::Incomplete(_) => anyhow::anyhow!("unreachable"), @@ -75,6 +66,35 @@ pub fn part1(input: &[u8]) -> anyhow::Result { Ok(total.to_string()) } -pub fn part2(_input: &[u8]) -> anyhow::Result { - anyhow::bail!("Not implemented") +pub fn part1(input: &[u8]) -> anyhow::Result { + parts_common(input, |(id, colors)| { + if colors[0] <= 12 && colors[1] <= 13 && colors[2] <= 14 { + u32::from(id) + } else { + 0 + } + }) +} + +pub fn part2(input: &[u8]) -> anyhow::Result { + parts_common(input, |(_, colors)| { + u32::from(colors[0]) * u32::from(colors[1]) * u32::from(colors[2]) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SAMPLE: &[u8] = include_bytes!("samples/02.txt"); + + #[test] + fn sample_part1() { + assert_eq!(part1(SAMPLE).unwrap(), "8"); + } + + #[test] + fn sample_part2() { + assert_eq!(part2(SAMPLE).unwrap(), "2286"); + } }