From a82498c4141728069d80418e26196193c451a1cd Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Sun, 22 Dec 2024 19:52:17 +0100 Subject: Add 2024 day 22 solutions --- 2024/22/puzzles.py | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 2024/22/puzzles.py (limited to '2024/22/puzzles.py') diff --git a/2024/22/puzzles.py b/2024/22/puzzles.py new file mode 100644 index 0000000..dff825f --- /dev/null +++ b/2024/22/puzzles.py @@ -0,0 +1,60 @@ +#!/usr/bin/python3 + +import collections +from typing import Deque, Iterable + + +type Diff = tuple[int, int, int, int] + + +def main() -> None: + with open("input", "r") as f: + xs = map(int, f.readlines()) + + # START PART 1 + print(sum(map(lastfrom, map(secrets, xs)))) + # END PART 1 START PART 2 + sums = collections.defaultdict(int) + for x in xs: + seen: set[Diff] = set() + dq: Deque[int] = collections.deque(maxlen=4) + + gen = map(lastdigit, secrets(x)) + last = next(gen) + + for _ in range(3): + n = next(gen) + dq.append(n - last) + last = n + + for n in gen: + dq.append(n - last) + if (t := tuple(dq)) not in seen: + seen.add(t) + sums[t] += n + last = n + dq.popleft() + + print(max(sums.values())) + # END PART 2 + + +def secrets(n: int) -> int: + for _ in range(2000): + n = (n ^ n<<6) & 0xFFFFFF + n = (n ^ n>>5) & 0xFFFFFF + n = (n ^ n<<11) & 0xFFFFFF + yield n + + +def lastdigit(n: int) -> int: + return n % 10 + + +def lastfrom[T](xs: Iterable[T]) -> T: + *_, x = xs + return x + + +if __name__ == "__main__": + main() -- cgit v1.2.3