From 3774cc95387d2d334de0dd192e611b548f0989aa Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Tue, 24 Dec 2024 17:48:48 +0100 Subject: Add 2024 day 24 part 1 solution --- 2024/24/puzzle-1.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100755 2024/24/puzzle-1.py diff --git a/2024/24/puzzle-1.py b/2024/24/puzzle-1.py new file mode 100755 index 0000000..d2d27ca --- /dev/null +++ b/2024/24/puzzle-1.py @@ -0,0 +1,46 @@ +#!/usr/bin/python3 + +import collections +from typing import Deque + + +def main() -> None: + with open("input", "r") as f: + head, tail = [s.split("\n") for s in f.read().split("\n\n")] + wires: dict[str, int] = {} + for line in head: + wire, val = line.split(": ") + wires[wire] = int(val) + todo: Deque[list[str]] = collections.deque() + for line in tail: + parts = line.split() + parts.pop(3) # Pop ‘->’ + todo.append(parts) + + while todo: + eqn = todo[0] + if not (eqn[0] in wires and eqn[2] in wires): + todo.rotate(-1) + continue + else: + todo.popleft() + lhs = wires[eqn[0]] + rhs = wires[eqn[2]] + match eqn[1]: + case 'AND': + x = lhs & rhs + case 'OR': + x = lhs | rhs + case 'XOR': + x = lhs ^ rhs + wires[eqn[3]] = x + + n = 0 + ends = ((k, v) for k, v in wires.items() if k[0] == 'z') + for k, v in sorted(ends, reverse=True): + n = n<<1 | v + print(n) + + +if __name__ == "__main__": + main() \ No newline at end of file -- cgit v1.2.3