summaryrefslogtreecommitdiffstats
path: root/8.py
diff options
context:
space:
mode:
Diffstat (limited to '8.py')
-rw-r--r--8.py39
1 files changed, 39 insertions, 0 deletions
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")
+ )
+ )
+)