Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

Advent of Code - 2023

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

Day 8: Haunted Wasteland

You're still riding a camel across Desert Island when you spot a sandstorm quickly approaching. When you turn to warn the Elf, she disappears before your eyes! To be fair, she had just finished warning you about ghosts a few minutes ago.

One of the camel's pouches is labeled "maps" - sure enough, it's full of documents (your puzzle input) about how to navigate the desert. At least, you're pretty sure that's what they are; one of the documents contains a list of left/right instructions, and the rest of the documents seem to describe some kind of network of labeled nodes.

It seems like you're meant to use the left/right instructions to navigate the network. Perhaps if you have the camel follow the same instructions, you can escape the haunted wasteland!

After examining the maps for a bit, two nodes stick out: AAA and ZZZ. You feel like AAA is where you are now, and you have to follow the left/right instructions until you reach ZZZ.

This format defines each node of the network individually. For example:

RL

AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
EEE = (EEE, EEE)
GGG = (GGG, GGG)
ZZZ = (ZZZ, ZZZ)

Starting with AAA, you need to look up the next element based on the next left/right instruction in your input. In this example, start with AAA and go right (R) by choosing the right element of AAA, CCC. Then, L means to choose the left element of CCC, ZZZ. By following the left/right instructions, you reach ZZZ in 2 steps.

Of course, you might not find ZZZ right away. If you run out of left/right instructions, repeat the whole sequence of instructions as necessary: RL really means RLRLRLRLRLRLRLRL... and so on. For example, here is a situation that takes 6 steps to reach ZZZ:

LLR

AAA = (BBB, BBB)
BBB = (AAA, ZZZ)
ZZZ = (ZZZ, ZZZ)

Starting at AAA, follow the left/right instructions. How many steps are required to reach ZZZ?

Read input

This time I modified my utils.py mini-library by adding a multisection reader. To use it, I need to pass a list of transformers that needs to match the length of the sections.

To parse today's inputs, the instructions are left as they are and for the node connections, I find all 3-length alphanumeric strings and store them in a dictionary so that first of them is the key and the last two are a tuple.

import re
from utils import read_multisection_input

def map_transformer(section):
    the_map = {}
    for line in section.split('\n'):
        key, left, right = re.findall(r'[0-9A-Z]{3}', line)
        the_map[key] = (left, right)
    return the_map

instructions, the_map = read_multisection_input(8, [str, map_transformer])

To solve this puzzle, I start with node AAA and loop until I have stepped into ZZZ.

To keep instructions running even if it runs out, I use itertools.cycle.

I them pattern match against the instructions and either take the first or the second of the next values. In part 2 I realized that pattern matching was bit too much here since we just have two values but I wanted to leave it here so you can compare it with the if/else choice in part 2.

from itertools import cycle

def solve_part_1(instructions, the_map):
    current = 'AAA'
    end = 'ZZZ'

    steps = 0
    for instruction in cycle(instructions):
        steps += 1
        match instruction:
            case 'L':
                current = the_map[current][0]
            case 'R':
                current = the_map[current][1]
        if current == end:
            return steps
            break

part_1 = solve_part_1(instructions, the_map)
print(f'Solution: {part_1}')
assert part_1 == 24253

Solution: 24253

Part 2

The sandstorm is upon you and you aren't any closer to escaping the wasteland. You had the camel follow the instructions, but you've barely left your starting position. It's going to take significantly more steps to escape!

What if the map isn't for people - what if the map is for ghosts? Are ghosts even bound by the laws of spacetime? Only one way to find out.

After examining the maps a bit longer, your attention is drawn to a curious fact: the number of nodes with names ending in A is equal to the number ending in Z! If you were a ghost, you'd probably just start at every node that ends with A and follow all of the paths at the same time until they all simultaneously end up at nodes that end with Z.

For example:

LR

11A = (11B, XXX)
11B = (XXX, 11Z)
11Z = (11B, XXX)
22A = (22B, XXX)
22B = (22C, 22C)
22C = (22Z, 22Z)
22Z = (22B, 22B)
XXX = (XXX, XXX)

Here, there are two starting nodes, 11A and 22A (because they both end with A). As you follow each left/right instruction, use that instruction to simultaneously navigate away from both nodes you're currently on. Repeat this process until all of the nodes you're currently on end with Z. (If only some of the nodes you're on end with Z, they act like any other node and you continue as normal.) In this example, you would proceed as follows:

  • Step 0: You are at 11A and 22A.
  • Step 1: You choose all of the left paths, leading you to 11B and 22B.
  • Step 2: You choose all of the right paths, leading you to 11Z and 22C.
  • Step 3: You choose all of the left paths, leading you to 11B and 22Z.
  • Step 4: You choose all of the right paths, leading you to 11Z and 22B.
  • Step 5: You choose all of the left paths, leading you to 11B and 22C.
  • Step 6: You choose all of the right paths, leading you to 11Z and 22Z.

So, in this example, you end up entirely on nodes that end in Z after 6 steps.

Simultaneously start on every node that ends with A. How many steps does it take before you're only on nodes that end with Z?

Today's second part was a very traditional Advent of Code second parter.

I started with a naive solution just to see if it would work. I found all the start nodes and walked the path. After an hour or so with no result, I decided it's time to use my brain and think.

Few years ago, I would have never solved this particular one. This year, thanks to my Advent of Code practice, I figured surprisingly fast what was happening and what needed to be done. I need to find the cycle with which each of these nodes starts to loop.

To do that, I use find_loop function that keeps track of each (step, node) combination. If I find a combination that already exists, I return since we know that it starts a new loop. In this function, I replaced the pattern matching with a idx = 0 if instruction == 'L' else 1. I'm not a big fan of these kind of inline if/else patterns but I feel this one is simple enough to understand that it's okay. In real life, it's a 50/50 whether I'd refactor it into something better.

I then have another helper function that finds the last node ending with Z since that's the one we are really interested in. This time, I use i in range(len(seq)) instead of looping over an reversed list because the lists are huge and this saves a ton of memory space and time.

To solve the puzzle, I loop over all the start nodes (nodes ending with A), find where they start looping, then find the step of the last z-ending node. I then calculate the least common multiple (lcm) which is the result.

Don't ask me how I know to use lcm. I've just ran into it enough times that I knew a puzzle of this nature probably uses it. Ask more detailed questions from someone who understands maths.

import math
from itertools import cycle


def find_loop(node, the_map, instructions):
    sequence = []
    step = 0
    instructions_length = len(instructions)
    for instruction in cycle(instructions):
        idx = 0 if instruction == 'L' else 1
        node = the_map[node][idx]

        mod_step = step % instructions_length
        if (mod_step, node) in sequence:
            return step, sequence

        sequence.append((mod_step, node))
        step += 1

def find_last_z_node(seq):
    for i in range(len(seq)):
        node = seq[-(i+1)][1]
        if node.endswith('Z'):
            return i

start_nodes = [key for key in the_map if key.endswith('A')]
last_z_in_each_loop = []
for node in start_nodes:
    loop_step, seq = find_loop(node, the_map, instructions)
    last_z_offset = find_last_z_node(seq)
    last_z_in_each_loop.append(loop_step - last_z_offset)

part_2 = math.lcm(*last_z_in_each_loop)
print(f'Solution: {part_2}')
assert part_2 == 12357789728873

Solution: 12357789728873

Few ways to get the next step

There are multiple different ways to map our next step based on an instruction and a map.

In each of these, the node refers to current position and the_map is a dictionary that looks like { "key": ("left_node", "right_node") }.

Which one to use depends on the case and how many different options there are. The if/else in either form is great if there's only 2 options. With more options, I'd use either a dictionary or pattern matching approach. Pattern matching gives the best "bang for buck" as it improves readability and enables doing more than just simple value mapping like guards or more complex patterns.

Using if/else:

if instruction == 'L':
    node = the_map[node][0]
else:
    node = the_map[node][1]

or with ternary operation:

index = 0 if instruction == 'L' else 1
node = the_map[node][idx]

Using pattern matching:

match instruction:
    case 'L':
        node = the_map[node][0]
    case 'R':
        node = the_map[node][1]

Using a dictionary

left_right = { 'left': 0, 'right': 1 }
node = the_map[node][left_right[instruction]]

Two stars!

16/50, we're on a really good path here.