Created
December 20, 2015 01:20
-
-
Save lwiecek/2f1679d2a42374069a20 to your computer and use it in GitHub Desktop.
day7
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import namedtuple | |
import copy | |
Gate = namedtuple('Gate', 'op in1 in2 out') | |
gates = set() # gates that have not been calculated yet | |
wires = {} # identifier -> value | |
def get_value(gate_in): | |
if gate_in is None: | |
return None | |
try: | |
return int(gate_in) | |
except ValueError: | |
return wires.get(gate_in) | |
def simulate(): | |
for gate in copy.copy(gates): | |
val1 = get_value(gate.in1) | |
val2 = get_value(gate.in2) | |
if (gate.op is None or gate.op == 'NOT') and val1 is not None: | |
if gate.op is None: | |
wires[gate.out] = val1 | |
else: # NOT | |
wires[gate.out] = 65535 - val1 | |
gates.remove(gate) | |
elif val1 is not None and val2 is not None: # 2-arg OP | |
if gate.op == 'AND': | |
wires[gate.out] = val1 & val2 | |
elif gate.op == 'OR': | |
wires[gate.out] = val1 | val2 | |
elif gate.op == 'LSHIFT': | |
wires[gate.out] = val1 << val2 | |
elif gate.op == 'RSHIFT': | |
wires[gate.out] = val1 >> val2 | |
gates.remove(gate) | |
with open('input7.txt') as f: | |
for line in f: | |
fragments = line.strip().split() | |
if len(fragments) == 5: | |
gate = Gate(fragments[1], fragments[0], fragments[2], fragments[4]) | |
elif len(fragments) == 4: | |
gate = Gate(fragments[0], fragments[1], None, fragments[3]) | |
elif len(fragments) == 3: | |
gate = Gate(None, fragments[0], None, fragments[2]) | |
gates.add(gate) | |
while wires.get('a') is None: | |
simulate() | |
print(wires['a']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment