diff --git a/challenges/2023/08-hauntedWasteland/main.py b/challenges/2023/08-hauntedWasteland/main.py index 23e5b04..08d39dd 100644 --- a/challenges/2023/08-hauntedWasteland/main.py +++ b/challenges/2023/08-hauntedWasteland/main.py @@ -1,6 +1,7 @@ import sys import re from functools import reduce +import math def parse(instr: str) -> tuple[str, dict[str, tuple[str, str]]]: @@ -41,7 +42,7 @@ def two(instr: str): if key[-1] == "A": cursors.append(key) - constraints = [] + loop_lengths = [] for start in cursors: cursor = start @@ -60,47 +61,11 @@ def two(instr: str): assert reduce(lambda acc, v: acc or v[0][-1] == "Z", history, False), f"{start} has no end condition" loop_start_key = (cursor, instruction_step) - - endpoint_at = None - for key in history: - if key[0][-1] == "Z": - endpoint_at = history[key] - _debug(key) - loop_starts_at = history[loop_start_key] - loop_length = (max(history.values()) - loop_starts_at) + 1 - _debug(f"{start} loops {loop_start_key} {loop_starts_at=} {endpoint_at=} {loop_length=}") - - constraints.append((loop_starts_at, endpoint_at - loop_starts_at, loop_length)) - - m = 0 - soln = None - - while True: - # _debug("---") - - if m % 1000 == 0: - _debug(m, end="\r") - - works = True - - for (s, i, l) in constraints: - x = (m-s-i)/l - - # _debug((s, i, l), x, (x < 0 or x % 1 != 0)) - - if x < 0 or not float(x).is_integer(): - works = False - break - - if works: - soln = m - break - - m += 1 - - return soln + loop_lengths.append((max(history.values()) - loop_starts_at) + 1) + + return math.lcm(*loop_lengths) def _debug(*args, **kwargs):