Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

Advent of Code - 2023

This is a solution to Day 2 of Advent of Code 2023.

Day 2: Cube Conundrum

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.

Read input

Today's puzzle was a lot of fun. Immediately when I saw the input syntax, I knew I'll be using two things I really enjoy: regular expressions and namedtuples.

namedtuples are a favorite of mine to model data structures in these puzzles. It works like a regular tuple but you can give it and its attributes names so it also works as documentation inside your code.

I start by creating a pattern for a single round (like 3 blue, 4 red) and named tuples for Game and Round.

A Game holds info about its id and any rounds played. A Round keeps track of the count for each color.

Then for each line, I do a series string manipulations and regex matchings to find the game's ID and individual values for each colored cubes in rounds.

Most of the work here actually goes to creating these data structures. With a properly mapped input -> data structure process, many times I find these puzzles become easier as I'm not manipulating the data or doing calculations directly with the raw data but just map it to code.

It turned out that this made Part 2 today practically free.

Let's take a look at that regex matching

PULLED_CUBES_PATTERN = r'((\d+) (blue|red|green))+'

Here we have a pattern of number with 1 or more digits (\d+), a single space ( ) and then one of the three colors (blue|red|green, the pipe | character means "or") and and finally we match more than one of these with the + at the end. And with the parentheses, we capture the value of the number and the value of the color.

When we do _, count, color = matches, the first result is the entire match (for example 3 green) so we skip it with _, the next one is the first capture (our number) and the last one is the second capture (the color).

Tuples are immutable

On line 19, we create a placeholder Round with all values zero. Since tuples are immutable, we cannot change individual values so we need to instead, take our existing one, change one of its values and store it into a new tuple.

With named tuples, we can do this with a _replace() method. It accepts keyword arguments with new values, so for example, we could say current_round._replace(blue=2) and it would return us a new tuple with the value of blue being 2 and everything else being the same.

Since we have our color as a variable, we can create a dictionary ({ color: int(count) }) and pass that as a **kwargs pattern. Any variable passed into a function with double asterisk before it, gets expanded into key=value named argument pairs.

import re
from collections import namedtuple

from utils import read_input

PULLED_CUBES_PATTERN = r'((\d+) (blue|red|green))+'

Game = namedtuple('Game', ['id', 'rounds'])
Round = namedtuple('Round', ['blue', 'red', 'green'])

def transformer(line):
    game_input, rounds_input = line.split(': ')
    game_id = game_input.strip().split(' ')[1]
    rounds = [round.strip() for round in rounds_input.split(';')]
    rounds_in_game = []

    for round in rounds:
        current_round = Round(blue=0, red=0, green=0)
        for matches in re.findall(PULLED_CUBES_PATTERN, round):
            # Filter out missing cube colors
            _, count, color = matches

            # Create a dictionary that can be used as **kwargs to `_replace` method
            update = { color: int(count) }
            current_round = current_round._replace(**update)

    game = Game(id=int(game_id), rounds=rounds_in_game)

    return game

games = read_input(2, transformer)

Part 1

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?

To find out which games are valid, I created a validate function that goes through each round in each game until it finds a rule-breaking round. With Python's for/else mechanic, I can check if the for loop finished without breaking (it will then enter the else branch) and if it did, add those to a list of valid games.

Finally, I sum all the ids of these valid games.

def validate(games):
    MAX_RED = 12
    MAX_GREEN = 13
    MAX_BLUE = 14
    valid_games = []
    for game in games:
        is_valid = True
        for round in game.rounds:
            if round.blue > MAX_BLUE or round.red > MAX_RED or round.green > MAX_GREEN:
    return sum(game.id for game in valid_games)

part_1 = validate(games)
print(f'Solution: {part_1}')
assert part_1 == 2683

Part 2

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?

The second part has a long explanation but since we have all the data parsed nicely into tuples, all we need to do, is to find the largest value for a game in each of its rounds and then multiple them together. Finally we sum all those power calculations across different games to get our result.

def calculate_power(game):
    min_green = max(round.green for round in game.rounds)
    min_blue = max(round.blue for round in game.rounds)
    min_red = max(round.red for round in game.rounds)
    return min_green * min_blue * min_red
def calculate_total_power(games):
    return sum(calculate_power(game) for game in games)
part_2 = calculate_total_power(games)
print(f'Solution: {part_2}')
assert part_2 == 49710

Two stars!

Another successful day with two stars. 4/50 done and Christmas is ever so closer to be a happy success.