-
Notifications
You must be signed in to change notification settings - Fork 0
/
intcode.py
47 lines (46 loc) · 2.2 KB
/
intcode.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
def extract(opcode):
a, b, c, de = opcode % 100000 // 10000, opcode % 10000 // 1000, opcode % 1000 // 100, opcode % 100
return a, b, c, de
def intcode(arr, pos=0, inp=[]):
base = 0
output = []
while True:
a, b, c, de = extract(arr[pos])
if de == 99:
return arr, pos, output
elif de == 1:
arr[arr[pos + 3] + base * (a // 2)] = (arr[pos + 1] if c == 1 else arr[arr[pos + 1] + base * (c // 2)]) + (arr[pos + 2] if b == 1 else arr[arr[pos + 2] + base * (b // 2)])
pos += 4
elif de == 2:
arr[arr[pos + 3] + base * (a // 2)] = (arr[pos + 1] if c == 1 else arr[arr[pos + 1] + base * (c // 2)]) * (arr[pos + 2] if b == 1 else arr[arr[pos + 2] + base * (b // 2)])
pos += 4
elif de == 3:
if not inp:
return arr, pos, output
arr[arr[pos + 1] + base * (c // 2)] = inp.pop(0)
pos += 2
elif de == 4:
res = (arr[pos + 1] if c == 1 else arr[arr[pos + 1] + base * (c // 2)])
output.append(res)
pos += 2
elif de == 5:
if (arr[pos + 1] if c == 1 else arr[arr[pos + 1] + base * (c // 2)]):
pos = (arr[pos + 2] if b == 1 else arr[arr[pos + 2] + base * (b // 2)])
else:
pos += 3
elif de == 6:
if not (arr[pos + 1] if c == 1 else arr[arr[pos + 1] + base * (c // 2)]):
pos = (arr[pos + 2] if b == 1 else arr[arr[pos + 2] + base * (b // 2)])
else:
pos += 3
elif de == 7:
arr[arr[pos + 3] + base * (a // 2)] = int((arr[pos + 1] if c == 1 else arr[arr[pos + 1] + base * (c // 2)]) < (arr[pos + 2] if b == 1 else arr[arr[pos + 2] + base * (b // 2)]))
pos += 4
elif de == 8:
arr[arr[pos + 3] + base * (a // 2)] = int((arr[pos + 1] if c == 1 else arr[arr[pos + 1] + base * (c // 2)]) == (arr[pos + 2] if b == 1 else arr[arr[pos + 2] + base * (b // 2)]))
pos += 4
elif de == 9:
base += (arr[pos + 1] if c == 1 else arr[arr[pos + 1] + base * (c // 2)])
pos += 2
else:
pos += 1