-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path08.py
67 lines (57 loc) · 1.28 KB
/
08.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
def read_app():
for line in open('input.txt'):
line = line.strip()
cmd, arg = line.split(' ')
yield (cmd, int(arg))
def find_loop(app):
acc = 0
ip = 0
visited = set()
while ip not in visited:
visited.add(ip)
cmd, arg = app[ip]
if cmd == 'acc':
acc += arg
ip += 1
elif cmd == 'jmp':
ip += arg
else:
ip += 1
return acc
def star1():
app = list(read_app())
print(find_loop(app))
def find_loop2(app):
acc = 0
ip = 0
visited = set()
while ip not in visited:
if ip >= len(app):
return False, acc
visited.add(ip)
cmd, arg = app[ip]
if cmd == 'acc':
acc += arg
ip += 1
elif cmd == 'jmp':
ip += arg
else:
ip += 1
return True, acc
def star2():
app = list(read_app())
for i in range(len(app)):
nextapp = list(app)
cmd, arg = nextapp[i]
if cmd == 'jmp':
nextapp[i] = ('nop', arg)
elif cmd == 'nop':
nextapp[i] = ('jmp', arg)
cycled, acc = find_loop2(nextapp)
if not cycled:
print(acc)
break
print('Star 1:')
star1()
print('Star 2:')
star2()