Created
December 7, 2015 12:38
-
-
Save jamesmcm/e8d264eea7f29aa4dd6d to your computer and use it in GitHub Desktop.
Advent Of Code 7 In Python
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
import re | |
#test input | |
inp="""123 -> x | |
456 -> y | |
x AND y -> d | |
x OR y -> e | |
x LSHIFT 2 -> f | |
y RSHIFT 2 -> g | |
NOT x -> h | |
NOT y -> i""" | |
#Define Operation Class | |
class Operation(object): | |
def __init__(self, s): | |
r=re.findall("([a-z0-9]+)?\s?([A-Z]+)?\s?([a-z0-9]*)\s([A-Z]+)?([a-z0-9]+)?\s?->\s([a-z]+)", s)[0] | |
#print r | |
self.equation = r | |
self.output=r[5] | |
if r[1]=='': | |
self.kind="ASSIGNMENT" | |
else: | |
self.kind=r[1] | |
self.dependencies=set() | |
self.lhs='' | |
self.rhs='' | |
if r[0]!='': | |
self.lhs=r[0] | |
if r[2]!='': | |
self.rhs=r[2] | |
if r[0]!='' and not r[0].isdigit(): | |
self.dependencies.add(r[0]) | |
if r[2]!='' and not r[2].isdigit(): | |
self.dependencies.add(r[2]) | |
def run(self, d): | |
if self.kind=="ASSIGNMENT": | |
if self.lhs.isdigit(): | |
d[self.output]=int(self.lhs) | |
else: | |
d[self.output]=d[self.lhs] | |
elif self.kind=="AND": | |
if self.lhs.isdigit(): | |
lhs=int(self.lhs) | |
else: | |
lhs=d[self.lhs] | |
if self.rhs.isdigit(): | |
rhs=int(self.rhs) | |
else: | |
rhs=d[self.rhs] | |
d[self.output]=lhs&rhs | |
elif self.kind=="OR": | |
if self.lhs.isdigit(): | |
lhs=int(self.lhs) | |
else: | |
lhs=d[self.lhs] | |
if self.rhs.isdigit(): | |
rhs=int(self.rhs) | |
else: | |
rhs=d[self.rhs] | |
d[self.output]=lhs|rhs | |
elif self.kind=="LSHIFT": | |
if self.lhs.isdigit(): | |
lhs=int(self.lhs) | |
else: | |
lhs=d[self.lhs] | |
d[self.output]=lhs << int(self.rhs) | |
elif self.kind=="RSHIFT": | |
if self.lhs.isdigit(): | |
lhs=int(self.lhs) | |
else: | |
lhs=d[self.lhs] | |
d[self.output]=lhs >> int(self.rhs) | |
elif self.kind=="NOT": | |
if self.rhs.isdigit(): | |
rhs=int(self.rhs) | |
else: | |
rhs=d[self.rhs] | |
d[self.output]=~rhs | |
ops=[] #Create operation objects | |
for x in inp.split("\n"): | |
print x | |
ops.append(Operation(x)) | |
solved =set() #Loop through operations checking dependencies | |
globald={} | |
while(len(ops)>0): | |
for op in ops: | |
if len(op.dependencies.difference(solved))==0: | |
print op.equation | |
op.run(globald) | |
solved.add(op.output) | |
ops.remove(op) | |
for k in globald.keys(): | |
if globald[k]<0: | |
globald[k]=globald[k]+65536 #fix signed integer stuff | |
print globald |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment