advent-of-code/src/holt59/aoc/2023/day8.py
Mikaël Capelle 87936d6422
All checks were successful
continuous-integration/drone/push Build is passing
Refactor code for API (#3)
Co-authored-by: Mikael CAPELLE <mikael.capelle@thalesaleniaspace.com>
Co-authored-by: Mikaël Capelle <capelle.mikael@gmail.com>
Reviewed-on: #3
2024-12-08 13:06:41 +00:00

31 lines
857 B
Python

import itertools
import math
from typing import Any, Iterator
from ..base import BaseSolver
class Solver(BaseSolver):
def solve(self, input: str) -> Iterator[Any]:
lines = input.splitlines()
sequence = lines[0]
nodes = {
p[0]: {d: n for d, n in zip("LR", p[1].strip("()").split(", "))}
for line in lines[2:]
if (p := line.split(" = "))
}
def path(start: str):
path = [start]
it_seq = iter(itertools.cycle(sequence))
while not path[-1].endswith("Z"):
path.append(nodes[path[-1]][next(it_seq)])
return path
# part 1
yield len(path(next(node for node in nodes if node.endswith("A")))) - 1
# part 2
yield math.lcm(*(len(path(node)) - 1 for node in nodes if node.endswith("A")))