advent-of-code/2024/24/one.py
2024-12-25 12:59:49 +01:00

48 lines
972 B
Python

#!/usr/bin/env python3
import functools
import sys
import typing
input_file = sys.argv[1]
with open(input_file) as fd:
lines = [line.rstrip() for line in fd.readlines()]
gates: dict[str, tuple[str, typing.Callable, str]] = dict()
varis: dict[str, int] = dict()
funs = {
"AND": int.__and__,
"OR": int.__or__,
"XOR": int.__xor__,
}
step = False
for line in lines:
if not line:
step = True
elif step:
a, op, b, _, dest = line.split()
fun = funs[op]
gates[dest] = (a, fun, b)
else:
dest, val = line.split(":")
varis[dest] = int(val)
@functools.cache
def get_var(var: str) -> int:
if var in varis:
return varis[var]
a, fun, b = gates[var]
avar = get_var(a)
bvar = get_var(b)
return fun(avar, bvar)
zees = sorted([key for key in gates.keys() if key.startswith("z")])
bits = reversed([str(get_var(key)) for key in zees])
res = int("".join(bits), base=2)
print(res)