From d97465d144e14e7b91d2efdda3fa2aaaca236394 Mon Sep 17 00:00:00 2001 From: Pat Thoyts Date: Sun, 3 Dec 2023 20:03:35 +0000 Subject: [PATCH] day2: [rust] part 2 --- day2/src/game.rs | 19 +++++++++++++++++++ day2/src/main.rs | 7 ++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/day2/src/game.rs b/day2/src/game.rs index 11c427c..37de463 100644 --- a/day2/src/game.rs +++ b/day2/src/game.rs @@ -1,5 +1,6 @@ use std::str::FromStr; use round::Round; +use std::cmp; #[derive(Debug, PartialEq, Eq)] pub struct Game { @@ -10,6 +11,18 @@ pub struct Game { #[derive(Debug, PartialEq, Eq)] pub struct ParseGameError; +impl Game { + pub fn power(&self) -> u32 { + let mut res = Round {red: 0, green: 0, blue: 0 }; + for round in self.rounds.iter() { + res.red = cmp::max(res.red, round.red); + res.green = cmp::max(res.green, round.green); + res.blue = cmp::max(res.blue, round.blue); + } + return res.red * res.green * res.blue; + } +} + impl FromStr for Game { type Err = ParseGameError; @@ -57,4 +70,10 @@ mod tests { ]}); assert_eq!(Game::from_str("Game 1: 20 red, 1 green, 2 blue; 2 green\n"), expected); } + + #[test] + fn test_game_power() { + let game = Game::from_str("Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green").unwrap(); + assert_eq!(game.power(), 48); + } } diff --git a/day2/src/main.rs b/day2/src/main.rs index 0b585a5..24f4ce5 100644 --- a/day2/src/main.rs +++ b/day2/src/main.rs @@ -42,12 +42,17 @@ fn main() -> Result<(), Box> { .collect::>(); let limits = Round { red: 12, green: 13, blue: 14 }; - let sum_ids: u32= games.into_iter() + let sum_ids: u32 = games.iter() .filter(|g| valid_game(g, &limits)) // .inspect(|g| print_game(g)) .map(|g| g.id) .sum(); println!("part 1: {}", sum_ids); + + let sum_power: u32 = games.into_iter() + .map(|g| g.power()) + .sum(); + println!("part 2: {}", sum_power); } Ok(()) } -- 2.23.0