2015/day07.py

49 lines
1.2 KiB
Python
Raw Permalink Normal View History

2022-12-04 02:42:29 +00:00
import fileinput
from collections import deque
input = []
for line in fileinput.input():
expression, wire = line.strip().split(" -> ")
input.append((expression.split(), wire))
def simulate(wires):
def get(signal):
if signal.isdigit():
return int(signal)
else:
return wires[signal]
queue = deque(input)
while queue:
expression, wire = queue.popleft()
if wire in wires:
continue
try:
match expression:
case [signal]:
wires[wire] = get(signal)
case ["NOT", signal]:
wires[wire] = ~get(signal)
case [left, "AND", right]:
wires[wire] = get(left) & get(right)
case [left, "OR", right]:
wires[wire] = get(left) | get(right)
case [left, "LSHIFT", right]:
wires[wire] = get(left) << get(right)
case [left, "RSHIFT", right]:
wires[wire] = get(left) >> get(right)
except KeyError:
queue.append((expression, wire))
return wires["a"]
part1 = simulate({})
print("part 1:", part1)
part2 = simulate({"b": part1})
print("part 2:", part2)