blob: d2719397f2ce13c293eca8bcc3fe675c3e9b7ca5 (
plain)
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
|
"""Day 8."""
with open("input") as f:
instructions = f.read().rstrip().split("\n")
def parse_instructions(instructions):
"""Parse Instructions."""
acc = 0
visited = set()
loc = 0
for x in range(len(instructions)):
try:
inst, val = instructions[loc].split(" ")
except IndexError:
if x == len(instructions):
return acc, False
else:
return acc, True
if loc in visited:
break
else:
visited.add(loc)
if inst == "jmp":
loc += int(val)
elif inst == "acc":
acc += int(val)
loc += 1
elif inst == "nop":
loc += 1
successful = x == len(instructions)
return acc, successful
def instruction_generator(instructions):
yield instructions
for x, line in enumerate(instructions):
inst, val = line.split(" ")
if inst == 'nop':
new = instructions.copy()
new[x] = f"jmp {val}"
yield new
elif inst == 'jmp':
new = instructions.copy()
new[x] = f"nop {val}"
yield new
# Part 1
acc, _ = parse_instructions(instructions)
print(acc)
# Part 2
for intset in list(instruction_generator(instructions)):
acc, successful = parse_instructions(intset)
if successful:
print(acc)
|