[Day 2] Cube Conundrum // Advent of Code 2023 (Python)
Solving Advent of Code 2023 Day 2 in Python: parsing cube game records to find possible games, then computing the power of the minimum cube sets for Part 2.

Cube Conundrum (via DALL-E 3)
Let’s try to solve Day 2 with Python!
Advent of Code
You’re launched high into the atmosphere! The apex of your trajectory just barely reaches the surface of a large island…adventofcode.com
Part One
# --- Day 2: Cube Conundrum ---
# --- Part One ---
You're launched high into the atmosphere! The apex of your trajectory just barely reaches the surface of a large island floating in the sky. You gently land in a fluffy pile of leaves. It's quite cold, but you don't see much snow. An Elf runs over to greet you.
The Elf explains that you've arrived at **Snow Island** and apologizes for the lack of snow. He'll be happy to explain the situation, but it's a bit of a walk, so you have some time. They don't get many visitors up here; would you like to play a game in the meantime?
As you walk, the Elf shows you a small bag and some cubes which are either red, green, or blue. Each time you play this game, he will hide a secret number of cubes of each color in the bag, and your goal is to figure out information about the number of cubes.
To get information, once a bag has been loaded with cubes, the Elf will reach into the bag, grab a handful of random cubes, show them to you, and then put them back in the bag. He'll do this a few times per game.
You play several games and record the information from each game (your puzzle input). Each game is listed with its ID number (like the 11 in Game 11: ...) followed by a semicolon-separated list of subsets of cubes that were revealed from the bag (like 3 red, 5 green, 4 blue).
For example, the record of a few games might look 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
In game 1, three sets of cubes are revealed from the bag (and then put back again). The first set is 3 blue cubes and 4 red cubes; the second set is 1 red cube, 2 green cubes, and 6 blue cubes; the third set is only 2 green cubes.
The Elf would first like to know which games would have been possible if the bag contained only 12 red cubes, 13 green cubes, and 14 blue cubes?
In the example above, games 1, 2, and 5 would have been possible if the bag had been loaded with that configuration. However, game 3 would have been impossible because at one point the Elf showed you 20 red cubes at once; similarly, game 4 would also have been impossible because the Elf showed you 15 blue cubes at once. If you add up the IDs of the games that would have been possible, you get 8.
Determine which games would have been possible if the bag had been loaded with only 12 red cubes, 13 green cubes, and 14 blue cubes. What is the sum of the IDs of those games?
This is quite interesting! We have to parse the game records here to find all possible games against the given combination and then return sum of all the elgibile game ids.
I first did some quick dirty iteration in ipython3 to break down a single game record:
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green

💭 Now, in a way you only need to check local maxima for Red, Green and Blue cubes from each game to check it’s eligibility against the given combination, which means, the only code that matters is to check:

As given in the example, for the following 5 games, if we were to check for all possible games for a bag containing 12 red cubes, 13 green cubes and 14 blue cubes ….
- 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
We can see that Game 3 and Game 4 couldn’t be possible as the record shows more number of red cubes and blue cubes present in our bag, respectively.
Let’s first write the above given example as our base test case:

Now based on your ipython scripting logic above, let’s write a class CubeGameAnalyzer along with helper methods.
I am feeling in mood to be a little object oriented!

And, we get:
[Running] python -u "/Users/jmalik/github/advent-of-code-2023/day_2/part_1_cube_conundrum.py"
Test passed: Sum of IDs is 8
Now since this is working correctly against our test code, let’s try it against the given puzzle input.
We can simply use f.readlines() to load the the game records from input.txt .
Here’s the final code:
# --- Day 2: Cube Conundrum ---
# --- Part one ---
class CubeGameAnalyzer:
def __init__(self, max_cubes):
self.max_cubes = max_cubes
def sum_of_possible_game_ids(self, games):
sum_ids = 0
for game in games:
try:
game_id, sequences = game.split(": ")
if self._is_game_possible(sequences):
sum_ids += int(game_id.split()[1])
except ValueError as e:
print(f"Error processing game data: {e}")
return sum_ids
def _is_game_possible(self, game_sequence):
sequences = game_sequence.split(";")
for sequence in sequences:
sequence = sequence.strip()
if not self._is_sequence_possible(sequence):
return False
return True
def _is_sequence_possible(self, sequence):
cubes = sequence.split(",")
for cube in cubes:
count, color = cube.strip().split()
if int(count) > self.max_cubes[color]:
return False
return True
def main():
# read games from the input file
with open("day_2/input.txt") as f:
games = f.readlines()
# calculate and display the sum of possible game IDs
max_cubes = {"red": 12, "green": 13, "blue": 14}
analyzer = CubeGameAnalyzer(max_cubes)
print(analyzer.sum_of_possible_game_ids(games))
def test_cube_game_analyzer():
games = [
"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",
]
max_cubes = {"red": 12, "green": 13, "blue": 14}
analyzer = CubeGameAnalyzer(max_cubes)
sum_of_ids = analyzer.sum_of_possible_game_ids(games)
assert sum_of_ids == 8, f"Test failed: Expected 8, got {sum_of_ids}"
print(f"Test passed: Sum of IDs is {sum_of_ids}")
if __name__ == "__main__":
# run the test function
test_cube_game_analyzer()
# execute the main function
main()
We get an answer once we run this.
Let’s put that up back in the Day 2 page and…..voila! 🎉

Day Two
## --- Part Two ---
The first half of this puzzle is complete! It provides one gold star: *
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?
So, we need to find the mininum set of cubes required meaning, we need to find the local maxima in each game record for all the sets.
I did some quick scripting to do a POC, and was able to write up a quick algo to get minimum number of cubes required for each color:

Translating this to pythonic code by removing some nesting using map filter mul functions:

We can see that our base testcase given in the question is now green! 💚
[Running] python -u "/Users/jmalik/github/advent-of-code-2023/day_2/part_2_cube_conundrum.py"
Test passed: Sum of Power of Games is 2286
Let’s just add a main() to load up the input.txt as get your puzzle input and our final code looks something like:
# --- Day 2: Cube Conundrum ---
# --- Part Two ---
from functools import reduce
from operator import mul
class CubeGameAnalyzer:
def __init__(self, games, max_cubes=None):
self.games = games
self.max_cubes = max_cubes
def sum_of_possible_game_ids(self):
sum_ids = 0
for game in self.games:
try:
game_id, sequences = game.split(": ")
if self._is_game_possible(sequences):
sum_ids += int(game_id.split()[1])
except ValueError as e:
print(f"Error processing game data: {e}")
return sum_ids
def sum_of_power_of_games(self):
sum_power_of_games = 0
for game in self.games:
game_sets = game.split(": ")[1].split("; ")
# init minimum cubes required for each color to zero
min_cubes_required = {"red": 0, "green": 0, "blue": 0}
# for each set of cubes in game_sets
for cubes in game_sets:
for count, color in map(str.split, cubes.split(", ")):
# update the min cube requirement for each color
min_cubes_required[color] = max(int(count), min_cubes_required[color])
# multiplying the minimum cube counts
game_power = reduce(mul, min_cubes_required.values(), 1)
sum_power_of_games += game_power
return sum_power_of_games
def _is_game_possible(self, game_sequence):
sequences = game_sequence.split(";")
for sequence in sequences:
sequence = sequence.strip()
if not self._is_sequence_possible(sequence):
return False
return True
def _is_sequence_possible(self, sequence):
cubes = sequence.split(",")
for cube in cubes:
count, color = cube.strip().split()
if int(count) > self.max_cubes[color]:
return False
return True
def main():
# read games from the input file
with open("day_2/input.txt") as f:
games = f.readlines()
analyzer = CubeGameAnalyzer(games)
print(analyzer.sum_of_power_of_games())
def test_cube_game_analyzer():
games = [
"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",
]
analyzer = CubeGameAnalyzer(games)
sum_of_power_of_games = analyzer.sum_of_power_of_games()
assert (
sum_of_power_of_games == 2286
), f"Test failed: Expected 2286, got {sum_of_power_of_games}"
print(f"Test passed: Sum of Power of Games is {sum_of_power_of_games}")
if __name__ == "__main__":
# run the test function
test_cube_game_analyzer()
# execute the main function
main()
Let’s run it! We do get a number and as soon as we put it on the Day 2/Part 2 textbox……

🎉🎉🎉
Here’s a glimpse of my notebook rough notes to think about this problem, I often like to write down the solution before coding it:

Rough notes
p.s: I am deliberating not adding answers here so you can actually spend some time trying to understand how we solved the problem!
Feel free to checkout code on my Github repo and try to set it up and run on your machine 👇
advent-of-code-2023/day_2 at main · jatinkrmalik/advent-of-code-2023
Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can…github.com
Keep reading
🎄Solve Advent of Code 2024 With Me!
Announcing a spoiler-free YouTube video series for Advent of Code 2024 that focuses on how to analyze and approach each puzzle, not just the answers.
The Redis Paradox: my DelhiFOSS 2.0 talk at IIT Delhi, written up
The written version of my DelhiFOSS 2.0 talk on Redis beyond caching: a short history of caches, live driver matching with GEO commands, and Pub/Sub.
Interview prep, senior edition: a system design checklist, one backtracking template and what loops grade on
My 2022 prep notes for senior and staff interviews: a system design checklist, one Python DFS for seven backtracking problems, rubrics and a STAR story bank.
Leave a comment