diff --git a/py/aoc2024/day20.py b/py/aoc2024/day20.py index 72c1b9db..426c0814 100644 --- a/py/aoc2024/day20.py +++ b/py/aoc2024/day20.py @@ -2,9 +2,7 @@ Day 20: Race Condition """ -from functools import partial -from itertools import takewhile -from operator import gt +from aoc2024.day20c import solve as _solve SAMPLE_INPUT = """ ############### @@ -42,17 +40,6 @@ def _getpath(data: str) -> list[tuple[tuple[int, int], int]]: stack.append(((y, x), path | {(y, x): len(path)})) -def _solve(path: list[tuple[tuple[int, int], int]], cheats: int, time: int) -> int: - return sum( - (distance := abs(y2 - y1) + abs(x2 - x1)) <= cheats - and distance + time <= abs(t2 - t1) - for i, ((y1, x1), t1) in enumerate(path) - for (y2, x2), t2 in takewhile( - partial(gt, ((y1 + cheats, x1 + 1),)), path[i + 1 :] - ) - ) - - def part1(data: str, time: int = 100) -> int: """ >>> counts = [part1(SAMPLE_INPUT, time) for time in (2, 4, 6, 8, 10, 12, 20, 36, 38, 40, 64)] diff --git a/py/aoc2024/day20c.py b/py/aoc2024/day20c.py new file mode 100644 index 00000000..33b6e75b --- /dev/null +++ b/py/aoc2024/day20c.py @@ -0,0 +1,29 @@ +# cython: boundscheck=False, wraparound=False, initializedcheck=False, embedsignature=True +import cython +from collections.abc import Sequence + + +@cython.ccall +def solve( + path: Sequence[tuple[tuple[int, int], int]], cheats: cython.int, time: cython.int +) -> cython.int: + count: cython.int = len(path) + i: cython.int + result: cython.int = 0 + for i in range(count): + y1: cython.int + x1: cython.int + t1: cython.int + (y1, x1), t1 = path[i] + j: cython.int + for j in range(i + 1, count): + y2: cython.int + x2: cython.int + t2: cython.int + (y2, x2), t2 = path[j] + if y2 > y1 + cheats or y2 == y1 + cheats and x2 > x1: + break + distance: cython.int = abs(y2 - y1) + abs(x2 - x1) + if distance <= cheats and distance + time <= abs(t2 - t1): + result += 1 + return result diff --git a/py/aoc2024/day22c.py b/py/aoc2024/day22c.py index a2e04ac2..9aeb1878 100644 --- a/py/aoc2024/day22c.py +++ b/py/aoc2024/day22c.py @@ -1,9 +1,5 @@ # cython: boundscheck=False, wraparound=False, initializedcheck=False, embedsignature=True # ruff: noqa: F821 -""" -Day 22: Monkey Market -""" - import cython from cython.parallel import prange from cython.cimports.libc.string import memset