Files
aocpy/2015/d7.py
2024-01-29 21:48:01 -05:00

91 lines
2.7 KiB
Python

from lib import *
data = open(0).read()
part_2 = False
if part_2:
gates = {"b": 16076}
else:
gates = {}
while "a" not in gates:
for line in data.splitlines():
lhs, rhs = line.split(" -> ")
if part_2 and rhs == "b":
continue
lhs = lhs.strip()
if "NOT" in lhs:
op, op1 = lhs.split(" ")
assert op == "NOT"
try:
op1 = int(op1)
gates[rhs] = ~op1 & 0xffff
except ValueError:
if op1 in gates and isinstance(gates[op1], int):
gates[rhs] = ~gates[op1] & 0xffff
elif "OR" in lhs:
op1, op, op2 = lhs.split(" ")
assert op == "OR"
try:
op1 = int(op1)
except ValueError:
if op1 in gates and isinstance(gates[op1], int):
op1 = gates[op1]
try:
op2 = int(op2)
except ValueError:
if op2 in gates and isinstance(gates[op2], int):
op2 = gates[op2]
if not (isinstance(op1, int) and isinstance(op2, int)):
continue
gates[rhs] = (op1 | op2)
elif "AND" in lhs:
op1, op, op2 = lhs.split(" ")
assert op == "AND"
try:
op1 = int(op1)
except ValueError:
if op1 in gates and isinstance(gates[op1], int):
op1 = gates[op1]
try:
op2 = int(op2)
except ValueError:
if op2 in gates and isinstance(gates[op2], int):
op2 = gates[op2]
if not (isinstance(op1, int) and isinstance(op2, int)):
continue
gates[rhs] = (op1 & op2)
elif "LSHIFT" in lhs:
op1, op, op2 = lhs.split(" ")
op2 = int(op2)
try:
op1 = int(op1)
except ValueError:
if op1 in gates:
op1 = gates[op1]
else:
continue
gates[rhs] = (op1 << op2) & 0xffff
elif "RSHIFT" in lhs:
op1, op, op2 = lhs.split(" ")
op2 = int(op2)
try:
op1 = int(op1)
except ValueError:
if op1 in gates:
op1 = gates[op1]
else:
continue
gates[rhs] = (op1 >> op2) & 0xffff
else:
try:
lhs = int(lhs)
gates[rhs] = lhs
except ValueError:
if lhs in gates:
gates[rhs] = gates[lhs]
print(gates["a"])