From 849ee38426c977e0dca8a5f43d5d97641d8a23a8 Mon Sep 17 00:00:00 2001 From: Tomasz Kramkowski Date: Fri, 8 Dec 2023 09:45:04 +0000 Subject: day 8 --- 8.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 8.py diff --git a/8.py b/8.py new file mode 100644 index 0000000..4e01e3c --- /dev/null +++ b/8.py @@ -0,0 +1,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") + ) + ) +) -- cgit v1.2.3-54-g00ecf