My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Update day12.py

+20 -17
+20 -17
2016/day12.py
··· 1 1 import fileinput 2 2 3 3 4 - def simulate(program, a=0, b=0, c=0, d=0): 4 + def reg_or_val(regs, x): 5 + try: 6 + return int(x) 7 + except ValueError: 8 + return regs[x] 9 + 10 + 11 + def emulate(program, a=0, b=0, c=0, d=0): 5 12 pc = 0 6 13 regs = {'a': a, 'b': b, 'c': c, 'd': d} 7 14 ··· 9 16 if pc >= len(program): 10 17 return regs 11 18 12 - inst = program[pc].split() 13 - 14 - if len(inst) == 2: 15 - cmd, x = inst 16 - y = None 17 - else: 18 - cmd, x, y = inst 19 + cmd, x, y = program[pc] 19 20 20 21 if cmd == 'cpy': 21 - regs[y] = int(x) if x.isdigit() else regs[x] 22 + regs[y] = reg_or_val(regs, x) 22 23 23 24 elif cmd == 'inc': 24 25 regs[x] += 1 ··· 27 28 regs[x] -= 1 28 29 29 30 elif cmd == 'jnz': 30 - x = int(x) if x.isdigit() else regs[x] 31 + x = reg_or_val(regs, x) 31 32 32 - if x == 0: 33 - pc += 1 34 - continue 35 - else: 33 + if x != 0: 36 34 pc += int(y) 37 35 continue 38 36 39 37 pc += 1 40 38 41 39 42 - PROGRAM = [line.strip() for line in fileinput.input()] 40 + PROGRAM = [] 43 41 44 - print "Value in register a:", simulate(PROGRAM)['a'] 45 - print "When setting c to 1:", simulate(PROGRAM, c=1)['a'] 42 + for line in fileinput.input(): 43 + # Add null argument to pad inc/dec instructions 44 + instruction = line + ' null' 45 + PROGRAM.append(instruction.split()[:3]) 46 + 47 + print "Value in register a:", emulate(PROGRAM)['a'] 48 + print "When setting c to 1:", emulate(PROGRAM, c=1)['a']