AOC 23 - Day 02 - Cube Conundrum
After landing in a pile of leaves on a floating island, you walk with an Elf and play a game involving a bag full of red, green and blue cubes.
Part 1
Rules
For part one of the challenge, we are given a list of games, which looks like this:
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
Each game is composed of multiple rounds, and each round is composed of a number of color cubes. For example in game one, there is 3 rounds: 3 blue, 4 red
, 1 red, 2 green, 6 blue
, and 2 green
.
We have to determine which games can be played with a specific quantity of cubes: 12 red
, 13 green
, and 14 blue
.
A game can be played only if it doesn't require more color cube than the available ones. For example, a game containing 10 red cubes, 14 green cubes and 15 blue cubes could not be played, as it doesn't match the requirement of at least 12 red cubes.
Code
The parsing part is the following:
:
:
:
:
:
=
=
, =
=
return
=
=
, =
return
Then, the logic consists of checking whether each game has the required cubes:
=
=
=
return
return False
return True
Part 2
Rules
We now need to determine the minimum number of cubes required to play each game.
For example, for game 1:
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
The minimum required cubes are 4 red, 2 green, 6 blue
.
Code
The process involves simply identifying the highest count of each color in every game.
=
=
=
=
return * *
=
return
Refactoring
We can notice than in both part 1 and part 2, we are only interested in the maximum value each color can have for a given game.
This means we can discard the handfuls
field from the Game
class, and instead just keep the max values, avoiding useless iteration each time to them.
By cleaning the dataclasses and the input part:
...
:
:
...
=
=
, =
=
=
=
=
return
We can now simplify part 1 and part 2:
=
=
=
return
=
return
return
return * *
All the code is available on github