-
Notifications
You must be signed in to change notification settings - Fork 0
/
day8.py
55 lines (44 loc) · 1.42 KB
/
day8.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from util import getLinesFromFile
def parseLineIntoInstruction(line):
instr, val = line.rstrip('\n').split()
return instr, int(val)
def executeInstruction(instruction, pointer, accumulator):
if instruction[0] == 'nop':
return pointer + 1, accumulator
elif instruction[0] == 'acc':
accumulator += instruction[1]
return pointer + 1, accumulator
elif instruction[0] == 'jmp':
return pointer + instruction[1], accumulator
print(instruction)
def runProgram(program):
instrPointer = 0
accumulator = 0
instructionsRun = set()
while instrPointer < len(program):
if instrPointer in instructionsRun:
print('infinite loop')
print(accumulator)
return False
instructionsRun.add(instrPointer)
instrPointer, accumulator = executeInstruction(program[instrPointer], instrPointer, accumulator)
print('program finished')
print(accumulator)
return True
input = getLinesFromFile('input.txt')
program = [parseLineIntoInstruction(line) for line in input]
#part1
runProgram(program)
#part2
for instr in [x for x in program if x[0] == 'nop']:
programCopy = program[:]
idx = programCopy.index(instr)
programCopy[idx] = ('jmp',programCopy[idx][1])
if runProgram(programCopy):
break
for instr in [x for x in program if x[0] == 'jmp']:
programCopy = program[:]
idx = programCopy.index(instr)
programCopy[idx] = ('nop',programCopy[idx][1])
if runProgram(programCopy):
break