2023 - Day 8 (Haunted Wasteland)

View puzzle description on AdventOfCode.com
Part 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python3

#Advent of Code
#2023 Day 8, Part 1
#Solution by James C. (https://github.com/JamesMCo)

import os, sys
sys.path.append(os.path.abspath("../.."))
import unittest, util.read
from util.tests import run

from itertools import cycle
import re

def solve(puzzle_input: list[str]) -> int:
    instructions = cycle(puzzle_input[0])
    graph: dict[str, tuple[str, str]] = {}
    node_definition: re.Pattern = re.compile(r"([^ ]+) = \(([^ ]+), ([^ ]+)\)")

    for line in puzzle_input[2:]:
        node, left, right = node_definition.match(line).groups()
        graph[node] = (left, right)

    current_node = "AAA"
    steps = 0
    while current_node != "ZZZ":
        current_node = graph[current_node][0 if next(instructions) == "L" else 1]
        steps += 1
    return steps

def main() -> tuple[str, int]:
    puzzle_input = util.read.as_lines()

    return "The number of steps required to reach ZZZ is {}.", solve(puzzle_input)

class AOC_Tests(unittest.TestCase):
    def test_ex1(self):
        return self.assertEqual(solve(["RL",
                                       "",
                                       "AAA = (BBB, CCC)",
                                       "BBB = (DDD, EEE)",
                                       "CCC = (ZZZ, GGG)",
                                       "DDD = (DDD, DDD)",
                                       "EEE = (EEE, EEE)",
                                       "GGG = (GGG, GGG)",
                                       "ZZZ = (ZZZ, ZZZ)"]), 2)

    def test_ex2(self):
        return self.assertEqual(solve(["LLR",
                                       "",
                                       "AAA = (BBB, BBB)",
                                       "BBB = (AAA, ZZZ)",
                                       "ZZZ = (ZZZ, ZZZ)"]), 6)

if __name__ == "__main__":
    run(main)
Part 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python3

#Advent of Code
#2023 Day 8, Part 2
#Solution by James C. (https://github.com/JamesMCo)

import os, sys
sys.path.append(os.path.abspath("../.."))
import unittest, util.read
from util.tests import run

from itertools import cycle
from math import lcm
import re

def solve(puzzle_input: list[str]) -> int:
    graph: dict[str, tuple[str, str]] = {}
    node_definition: re.Pattern = re.compile(r"([^ ]+) = \(([^ ]+), ([^ ]+)\)")

    for line in puzzle_input[2:]:
        node, left, right = node_definition.match(line).groups()
        graph[node] = (left, right)

    def find_cycle(start_node: str) -> int:
        # After reading through some discussions on the subreddit, I found that
        # more assumptions could be made about the graphs given as inputs:
        #
        # - The routes given by the inputs will always cycle
        # - The cycle will only contain one **Z node
        # - The cycle for a given **A node is not shared
        #   by any other **A node
        # - The length from the **A node to the **Z is the
        #   same as the length of **Z to **Z in the cycle
        #
        # These assumptions mean that the approach to finding the cycle is
        # simpler than I originally implemented. Instead, we can find the
        # number of steps needed to reach the **Z node and return that.
        # Obviously, this wouldn't work for any arbitrary graph, but for
        # those given as puzzle inputs, it should be fine.

        instructions = cycle(puzzle_input[0])
        current_node = start_node
        steps = 0
        while not current_node.endswith("Z"):
            current_node = graph[current_node][0 if next(instructions) == "L" else 1]
            steps += 1
        return steps

    return lcm(*map(find_cycle, filter(lambda n: n.endswith("A"), graph)))

def main() -> tuple[str, int]:
    puzzle_input = util.read.as_lines()

    return "The number of steps required to reach before all nodes end with Z is {}.", solve(puzzle_input)

class AOC_Tests(unittest.TestCase):
    def test_ex1(self):
        return self.assertEqual(solve(["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)"]), 6)

if __name__ == "__main__":
    run(main)
Return to solution index