adventofcode-2016/12/part01.py

81 lines
2.0 KiB
Python
Raw Normal View History

2018-01-25 16:47:09 +01:00
#!/usr/bin/env python
import re
import argparse
RE_CPY = re.compile(r'^cpy (.*) (.)')
RE_INC = re.compile(r'^inc (.)')
RE_DEC = re.compile(r'^dec (.)')
RE_JNZ = re.compile(r'^jnz (.*) (-?\d+)')
INSTRUCTIONS = []
REGISTER = {'a': 0, 'b': 0, 'c': 0, 'd': 0 }
def instruction_cpy(k, v):
global REGISTER
if v in REGISTER:
v = REGISTER[v]
REGISTER[k] = int(v)
return 1
def instruction_inc(k):
global REGISTER
REGISTER[k] += 1
return 1
def instruction_dec(k):
global REGISTER
REGISTER[k] -= 1
return 1
def instruction_jnz(k, v):
global REGISTER
if k in REGISTER:
if REGISTER[k]:
return v
elif(int(k)):
return v
return 1
def load_file(filename):
with open(filename) as f:
for line in f:
yield line.strip()
def main(args):
for LINE in load_file(args.input):
match = RE_CPY.match(LINE)
if match:
INSTRUCTIONS.append({'values': [match.group(2), match.group(1)], 'function': instruction_cpy})
continue
match = RE_INC.match(LINE)
if match:
INSTRUCTIONS.append({'values': [match.group(1)], 'function': instruction_inc})
continue
match = RE_DEC.match(LINE)
if match:
INSTRUCTIONS.append({'values': [match.group(1)], 'function': instruction_dec})
continue
match = RE_JNZ.match(LINE)
if match:
INSTRUCTIONS.append({'values': [match.group(1), int(match.group(2))], 'function': instruction_jnz})
continue
raise Exception("line not parsable: {}". format(LINE))
line = 0
while True:
if line >= len(INSTRUCTIONS):
break
code = INSTRUCTIONS[line]
line += code['function'](*code['values'])
print(REGISTER['a'])
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='AdventOfCode 2016 Day 01')
parser.add_argument('--input', '-i', action='store', required=True, help='input file')
args = parser.parse_args()
main(args)