-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday09.py
65 lines (57 loc) · 1.81 KB
/
day09.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
from collections import defaultdict
with open("input.txt") as f:
inp = [int(x) for x in f.read().split(",")]
def run(p):
p = defaultdict(int, {i: a for i, a in enumerate(p)})
def get(offset):
mode = (instruction // 10 ** (1 + offset)) % 10
if mode == 0:
return p[index + offset]
elif mode == 1:
return index + offset
elif mode == 2:
return p[index + offset] + relative_base
else:
assert False, f"invalid mode: {mode}"
index = 0
relative_base = 0
while True:
instruction = p[index]
opcode = instruction % 100
if opcode == 1: # add
p[get(3)] = p[get(1)] + p[get(2)]
index += 4
elif opcode == 2: # mult
p[get(3)] = p[get(1)] * p[get(2)]
index += 4
elif opcode == 3: # input
p[get(1)] = int(input("enter: "))
index += 2
elif opcode == 4: # output
print(f"output: {p[get(1)]}")
index += 2
elif opcode == 5: # jump nonzero
if p[get(1)] != 0:
index = p[get(2)]
else:
index += 3
elif opcode == 6: # jump zero
if p[get(1)] == 0:
index = p[get(2)]
else:
index += 3
elif opcode == 7: # less than
p[get(3)] = int(p[get(1)] < p[get(2)])
index += 4
elif opcode == 8: # equals
p[get(3)] = int(p[get(1)] == p[get(2)])
index += 4
elif opcode == 9: # update relative base
relative_base += int(p[get(1)])
index += 2
elif opcode == 99: # halt
print("halt")
break
else:
assert False, f"invalid opcode: {opcode}"
run(inp)