-
Notifications
You must be signed in to change notification settings - Fork 2
/
Tag_08.py
51 lines (39 loc) · 1.21 KB
/
Tag_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
import time
def puzzle_einlesen(datei):
with open(datei) as f:
return [zeile.strip().split() for zeile in f]
class Opcode:
def __init__(self, puzzle):
self.prog = puzzle.copy()
self.pc = 0
self.acc = 0
def step(self):
if self.pc >= len(self.prog): return self.acc
opc, val = self.prog[self.pc]
if opc == 'acc': self.acc += int(val)
if opc == 'jmp': self.pc += int(val)
if opc != 'jmp': self.pc += 1
def löse(puzzle):
opcode = Opcode(puzzle)
executed = set()
while True:
if opcode.pc in executed: return opcode.acc
executed.add(opcode.pc)
opcode.step()
def löse2(puzzle):
nopOrjmp = [i for i, (opc,_) in enumerate(puzzle) if opc in ('jmp','nop')]
for i in nopOrjmp:
puzzle[i][0] = 'jmp' if puzzle[i][0] == 'nop' else 'nop'
executed = set()
opcode = Opcode(puzzle)
while True:
if opcode.pc in executed: break
executed.add(opcode.pc)
e = opcode.step()
if e: return e
puzzle[i][0] = 'jmp' if puzzle[i][0] == 'nop' else 'nop'
puzzle = puzzle_einlesen('Tag_08.txt')
start = time.perf_counter()
print(löse(puzzle), time.perf_counter()-start)
start = time.perf_counter()
print(löse2(puzzle), time.perf_counter()-start)