Day 8 - Advent of Code 2023

Working solutions for the day 8 puzzles.

Part One

""" day_08_01.py """

# usage: python3 day_08_01.py < input

import sys
from itertools import cycle


instructions = input()
input()

network = {}
for line in sys.stdin:
    node, other = line.split(' = ')
    left, right = other[1:-2].split(', ')
    network[node] = {'L': left, 'R': right}

position, steps = 'AAA', 0
for instruction in cycle(instructions):
    position = network[position][instruction]
    steps += 1
    if position == 'ZZZ':
        break

print(steps)

Part Two

""" day_08_02.py """

# usage: python3 day_08_02.py < input

import sys
from itertools import cycle
from math import lcm


instructions = input()
input()

network = {}
for line in sys.stdin:
    node, other = line.split(' = ')
    left, right = other[1:-2].split(', ')
    network[node] = {'L': left, 'R': right}

answer = 1
for node in [i for i in network if i.endswith('A')]:
    position, steps = node, 0
    for instruction in cycle(instructions):
        position = network[position][instruction]
        steps += 1
        if position.endswith('Z'):
            break
    answer = lcm(answer, steps)

print(answer)