From 51b5a859fbed04236861d424b6795de92868bcca Mon Sep 17 00:00:00 2001 From: Justin Wernick Date: Sat, 2 Dec 2023 16:13:25 +0200 Subject: Day 2 --- 2023/src/bin/day_2.rs | 104 ++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 97 insertions(+), 7 deletions(-) (limited to '2023/src/bin') diff --git a/2023/src/bin/day_2.rs b/2023/src/bin/day_2.rs index b3a610b..6f19c1d 100644 --- a/2023/src/bin/day_2.rs +++ b/2023/src/bin/day_2.rs @@ -1,19 +1,109 @@ -use nom::IResult; +use nom::{ + bytes::complete::tag, + character::complete::{alpha1, line_ending, u32 as nom_u32}, + combinator::map, + multi::separated_list1, + sequence::tuple, + IResult, +}; use std::fs; fn main() -> Result<(), Box> { let input = fs::read_to_string("inputs/day_2.txt")?; - let parsed = Example::parser(&input).unwrap().1; - dbg!(&parsed); + let parsed = Games::parser(&input).unwrap().1; + let max_pull = Pull { + red: 12, + green: 13, + blue: 14, + }; + dbg!(&parsed.valid_game_id_sum(&max_pull)); + dbg!(&parsed.power_sum()); Ok(()) } #[derive(Debug)] -struct Example; +struct Games(Vec); -impl Example { - fn parser(_input: &str) -> IResult<&str, Self> { - todo!() +#[derive(Debug)] +struct Game { + id: u32, + pulls: Vec, +} + +#[derive(Debug, Default)] +struct Pull { + red: u32, + green: u32, + blue: u32, +} + +impl Games { + fn parser(input: &str) -> IResult<&str, Self> { + map(separated_list1(line_ending, Game::parser), Games)(input) + } + + fn valid_game_id_sum(&self, max_pull: &Pull) -> u32 { + self.0 + .iter() + .filter(|game| game.is_valid(max_pull)) + .map(|game| game.id) + .sum() + } + + fn power_sum(&self) -> u32 { + self.0.iter().map(|game| game.min_pull().power()).sum() + } +} + +impl Game { + fn parser(input: &str) -> IResult<&str, Self> { + map( + tuple(( + tag("Game "), + nom_u32, + tag(": "), + separated_list1(tag("; "), Pull::parser), + )), + |(_, id, _, pulls)| Game { id, pulls }, + )(input) + } + + fn is_valid(&self, max_pull: &Pull) -> bool { + self.pulls.iter().all(|pull| { + pull.red <= max_pull.red && pull.blue <= max_pull.blue && pull.green <= max_pull.green + }) + } + + fn min_pull(&self) -> Pull { + Pull { + red: self.pulls.iter().map(|p| p.red).max().unwrap_or(0), + blue: self.pulls.iter().map(|p| p.blue).max().unwrap_or(0), + green: self.pulls.iter().map(|p| p.green).max().unwrap_or(0), + } + } +} + +impl Pull { + fn parser(input: &str) -> IResult<&str, Self> { + map( + separated_list1(tag(", "), tuple((nom_u32, tag(" "), alpha1))), + |stones| { + let mut pull = Pull::default(); + for (quantity, _, colour) in stones { + match colour { + "red" => pull.red += quantity, + "blue" => pull.blue += quantity, + "green" => pull.green += quantity, + other => panic!("Unexpected colour, {}", other), + }; + } + pull + }, + )(input) + } + + fn power(&self) -> u32 { + self.red * self.blue * self.green } } -- cgit v1.2.3