Iterative solution for December 7th 2015
This commit is contained in:
parent
e6a2fa044d
commit
894f3a5f4f
|
@ -0,0 +1,59 @@
|
|||
#!/usr/bin/env python3
|
||||
import sys
|
||||
from pprint import pprint
|
||||
wires = {}
|
||||
instructions = [l.strip().split(' -> ') for l in sys.stdin.readlines()]
|
||||
instructions = [(instruction.split(' '), dest) for instruction, dest in instructions]
|
||||
|
||||
def get_value(text):
|
||||
if text.isdigit():
|
||||
return int(text)
|
||||
return wires.get(text)
|
||||
|
||||
def parse(line):
|
||||
words, dest = line
|
||||
if len(words) == 1:
|
||||
if words[0].isdigit() and dest in wires:
|
||||
print('Ignoring redefinition of wire {} to {} (already set to {})'.format(
|
||||
dest, words[0], wires[dest]))
|
||||
return False
|
||||
value = get_value(words[0])
|
||||
if value is None:
|
||||
return True
|
||||
wires[dest] = value
|
||||
return False
|
||||
elif len(words) == 2 and words[0] == 'NOT':
|
||||
value = get_value(words[1])
|
||||
if value is None:
|
||||
return True
|
||||
wires[dest] = ~value & 0xffff
|
||||
return False
|
||||
elif len(words) == 3:
|
||||
a, gate, b = words
|
||||
a, b = get_value(a), get_value(b)
|
||||
if a is None or b is None:
|
||||
return True
|
||||
if gate == 'AND':
|
||||
wires[dest] = a & b
|
||||
elif gate == 'OR':
|
||||
wires[dest] = a | b
|
||||
elif gate == 'LSHIFT':
|
||||
wires[dest] = a << b
|
||||
elif gate == 'RSHIFT':
|
||||
wires[dest] = a >> b
|
||||
else:
|
||||
raise NotImplementedError
|
||||
return False
|
||||
else:
|
||||
raise NotImplementedError
|
||||
|
||||
def find_wire(name, data):
|
||||
while name not in wires:
|
||||
data = list(filter(parse, data))
|
||||
return wires[name]
|
||||
|
||||
part_one = find_wire('a', instructions)
|
||||
print('Part 1:', part_one)
|
||||
wires = {'b': part_one}
|
||||
part_two = find_wire('a', instructions)
|
||||
print('Part 2:', part_two)
|
Loading…
Reference in New Issue