From b9247c9eaf6f63830eb9b70c1159bd67dcada334 Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Tue, 5 Dec 2023 13:25:11 -0800 Subject: [PATCH] day2: problem 2 solution --- 2/src/main.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/2/src/main.rs b/2/src/main.rs index 60b241e..f4f56b8 100644 --- a/2/src/main.rs +++ b/2/src/main.rs @@ -165,6 +165,51 @@ fn problem1(input: InputIter) -> u64 { } // PROBLEM 2 solution -fn problem2(input: InputIter) -> u64 { - 0 + +// --- Part Two --- + +// The Elf says they've stopped producing snow because they aren't getting any water! He +// isn't sure why the water stopped; however, he can show you how to get to the water +// source to check it out for yourself. It's just up ahead! + +// As you continue your walk, the Elf poses a second question: in each game you played, +// what is the fewest number of cubes of each color that could have been in the bag to +// make the game possible? + +// Again consider the example games from earlier: + +// Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 +// green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, +// 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 +// blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green + +// In game 1, the game could have been played with as few as 4 red, 2 green, and 6 +// blue cubes. If any color had even one fewer cube, the game would have been +// impossible. Game 2 could have been played with a minimum of 1 red, 3 green, and 4 +// blue cubes. Game 3 must have been played with at least 20 red, 13 green, and 6 +// blue cubes. Game 4 required at least 14 red, 3 green, and 15 blue cubes. Game 5 +// needed no fewer than 6 red, 3 green, and 2 blue cubes in the bag. + +// The power of a set of cubes is equal to the numbers of red, green, and blue cubes +// multiplied together. The power of the minimum set of cubes in game 1 is 48. In games +// 2-5 it was 12, 1560, 630, and 36, respectively. Adding up these five powers produces +// the sum 2286. + +// For each game, find the minimum set of cubes that must have been present. What is the +// sum of the power of these sets? + + +// Minimum power = maximum seen of each colour across all games, r * g * b +fn problem2_game_minimum_power(game: &GameResult) -> u64 { + // Could be done in one pass, but this is cleaner using Iter methods + let max_r = game.results.iter().map(|c| c.red).max().unwrap(); + let max_g = game.results.iter().map(|c| c.green).max().unwrap(); + let max_b = game.results.iter().map(|c| c.blue).max().unwrap(); + + max_r * max_g * max_b +} + +fn problem2(input: InputIter) -> u64 { + let games = input.map(|l| GameResult::from(l.unwrap().as_str())); + games.fold(0u64, |accum, val| accum + problem2_game_minimum_power(&val)) }