AdventOfCode/2015/07/solution.py

69 lines
2.1 KiB
Python

#!/bin/python3
import sys,re
from pprint import pprint
sys.path.insert(0, '../../')
from fred import list2int,get_re,nprint,lprint,loadFile,convert_list
input_f = 'input'
part = 1
#########################################
# #
# Part 1 #
# #
#########################################
# need to use recursion. Should backtrack to a value when it has been lit
def parse(lst:str):
if 'AND' in lst or 'OR' in lst or 'SHIFT' in lst:
t = get_re(r"^(.+) (AND|OR|[L|R]SHIFT) (.+) -> (.+)",lst)
return convert_list([t.group(2), t.group(1),t.group(3),t.group(4)])
elif 'NOT' in lst:
t = get_re(r"^NOT (.+) -> (.+)",lst)
return convert_list(['NOT',t.group(1),t.group(2)])
else:
t = get_re(r"^(.+) -> (.+)",lst)
return convert_list(['SET',t.group(1),t.group(2)])
def v_return(x,values):
if isinstance(x, str):
if x not in values:
return 0 # the values is not 0 if it hasn't been used.
else:
return values[x]
return x
if part == 1:
instructions = loadFile(input_f)
values = {}
for i in instructions:
t = parse(i)
#print(i)
if t[0] == 'SET':
values[t[2]] = v_return(t[1],values)
elif t[0] == 'AND':
values[t[3]] = v_return(t[1],values) & v_return(t[2],values)
elif t[0] == 'OR':
values[t[3]] = v_return(t[1],values) | v_return(t[2],values)
elif t[0] == 'LSHIFT':
values[t[3]] = v_return(t[1],values) << v_return(t[2],values)
elif t[0] == 'RSHIFT':
values[t[3]] = v_return(t[1],values) >> v_return(t[2],values)
elif t[0] == 'NOT':
values[t[2]] = 65535-v_return(t[1],values)
#pprint(values)
#input()
pprint(values['a'])
#########################################
# #
# Part 2 #
# #
#########################################
if part == 2:
exit()