My Advent of Code solutions in Python.
kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code
python
1import fileinput
2from copy import deepcopy
3from utils import parse_nums
4
5TAPE = []
6
7for line in fileinput.input():
8 ins = line.split(' ')[0]
9 TAPE.append([ins, parse_nums(line)])
10
11
12def emulate(tape, pc=0, acc=0):
13 """Returns (acc, pc, loop_detected)"""
14 seen = set()
15 while pc < len(tape):
16 if pc in seen:
17 return (acc, pc, True)
18 else:
19 seen.add(pc)
20
21 ins, ops = tape[pc]
22
23 if ins == 'acc':
24 acc += ops[0]
25 pc += 1
26 elif ins == 'jmp':
27 pc += ops[0]
28 else:
29 pc += 1
30
31 return (acc, pc, False)
32
33
34print "ACC at repeated instruction:", emulate(TAPE)[0]
35
36for i in range(len(TAPE)):
37 tape = deepcopy(TAPE)
38
39 if tape[i][0] == 'acc':
40 continue
41 else:
42 if tape[i][0] == 'jmp':
43 tape[i][0] = 'nop'
44 else: # ins == 'nop'
45 tape[i][0] = 'jmp'
46
47 acc, pc, loop_detected = emulate(tape)
48 if not loop_detected:
49 print "ACC with modified termination:", acc