summaryrefslogtreecommitdiffstats
path: root/8.py
blob: 4e01e3cc01579b468f56dd5f765dc8a5426eb879 (plain)
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
# pyright: strict
import math
from collections.abc import Callable
from itertools import cycle
from sys import stdin

instructions, tree = stdin.read().rstrip("\n").split("\n\n")

nodes: dict[str, tuple[str, str]] = dict()
for n in tree.split("\n"):
    k, v = n.split(" = ")
    l, r = v.strip("()").split(", ")
    nodes[k] = (l, r)


def solve(
    nodes: dict[str, tuple[str, str]],
    start: str,
    end_cond: Callable[[str], bool],
    instructions: str,
) -> int:
    current = start
    for n, ins in enumerate(cycle(instructions)):
        if end_cond(current):
            return n
        current = nodes[current][0 if ins == "L" else 1]
    return 0


print(solve(nodes, "AAA", lambda c: c == "ZZZ", instructions))
print(
    math.lcm(
        *(
            solve(nodes, s, lambda c: c.endswith("Z"), instructions)
            for s in nodes.keys()
            if s.endswith("A")
        )
    )
)