-
Notifications
You must be signed in to change notification settings - Fork 0
/
12_8.py
89 lines (66 loc) · 1.58 KB
/
12_8.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
84
85
86
87
88
89
import sys
DEBUG = '-v' in sys.argv
if DEBUG: sys.argv.remove('-v')
def dprint(*args, **kwargs):
if DEBUG: print(*args, **kwargs)
INPUT = 'num8.txt' if len(sys.argv) == 1 else sys.argv[1]
# import numpy as np
# import scipy as sp
def parse(lines):
out = []
for l in lines:
l = l.strip()
op, arg = l.split()
arg = int(arg)
out.append((op, arg))
return out
# parse = parse_by_blank
def solve_1(data):
i = 0
acc = 0
seen = set()
while i not in seen:
seen.add(i)
op, arg = data[i]
if op == 'acc':
acc += arg
i += 1
elif op == 'nop':
i += 1
elif op == 'jmp':
i += arg
return acc
def test(data):
i = 0
acc = 0
seen = set()
while i not in seen:
seen.add(i)
op, arg = data[i]
if op == 'acc':
acc += arg
i += 1
elif op == 'nop':
i += 1
elif op == 'jmp':
i += arg
if i == len(data):
return acc
return None
def switch(op):
return 'nop' if op == 'jmp' else 'jmp'
def solve_2(data):
for i in range(len(data)):
copy = list(data)
op, arg = copy[i]
if op not in ('nop', 'jmp'): continue
copy[i] = (switch(op), arg)
result = test(copy)
if result is not None: return result
if __name__ == "__main__":
with open(INPUT) as f:
data = parse(f.readlines())
print('sol 1:', solve_1(data))
print()
f.seek(0)
print('sol 2:', solve_2(data))