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