-
Notifications
You must be signed in to change notification settings - Fork 0
/
day08.py
83 lines (76 loc) · 2.01 KB
/
day08.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
inp_f = open("input/day8.txt", "r")
inp = inp_f.read()
inp_list = [line for line in inp.split("\n") if line != ""]
def part1():
idx = 0
lines = []
acc = 0
while True:
if idx in lines:
return acc
line = inp_list[idx]
lines.append(idx)
instr = line.split(" ")
if instr[0] == "nop":
idx += 1
elif instr[0] == "acc":
change = int(instr[1][1:])
if instr[1][0] == "+":
acc += change
else:
acc -= change
idx += 1
elif instr[0] == "jmp":
change = int(instr[1][1:])
if instr[1][0] == "+":
idx += change
else:
idx -= change
return -1
def tryIt(inps):
idx = 0
lines = []
acc = 0
while True:
if idx in lines:
return -1 # infinite loop
if idx == len(inps):
return acc
line = inps[idx]
lines.append(idx)
instr = line.split(" ")
if instr[0] == "nop":
idx += 1
elif instr[0] == "acc":
change = int(instr[1][1:])
if instr[1][0] == "+":
acc += change
else:
acc -= change
idx += 1
elif instr[0] == "jmp":
change = int(instr[1][1:])
if instr[1][0] == "+":
idx += change
else:
idx -= change
return -1
def part2():
for i, line in enumerate(inp_list):
instr = line.split(" ")[0]
if instr == "acc":
continue
val = line.split(" ")[1]
inps = inp_list.copy()
if instr == "nop":
inps[i] = "jmp " + val
trying = tryIt(inps)
if trying != -1:
return trying
if instr == "jmp":
inps[i] = "nop " + val
trying = tryIt(inps)
if trying != -1:
return trying
if __name__ == "__main__":
print(part2())