-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintcode3.py
executable file
·91 lines (70 loc) · 1.81 KB
/
intcode3.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
def decode_opcode(value):
op = value % 100
value = value // 100
argmode = []
for i in range(3):
argmode.append(value % 10)
value = value // 10
return op, argmode
def get_val(ints, position, mode):
if mode == 0:
return ints[position]
elif mode == 1:
return position
else:
print("What the fuck", file=sys.stderr)
exit(1)
def run(ints, input):
pos = 0
while True:
op, argmode = decode_opcode(ints[pos])
if op == 1:
arg1 = ints[pos+1]
arg2 = ints[pos+2]
arg3 = ints[pos+3]
pos += 4
ints[arg3] = get_val(ints, arg1, argmode[0]) + get_val(ints, arg2, argmode[1])
elif op == 2:
arg1 = ints[pos+1]
arg2 = ints[pos+2]
arg3 = ints[pos+3]
pos += 4
ints[arg3] = get_val(ints, arg1, argmode[0]) * get_val(ints, arg2, argmode[1])
elif op == 3:
arg = ints[pos+1]
pos += 2
ints[arg] = input.pop(0)
elif op == 4:
arg = ints[pos+1]
pos += 2
print("Opcode 4: {}".format(get_val(ints, arg, argmode[0])))
elif (op == 5) or (op == 6):
arg1 = ints[pos+1]
arg2 = ints[pos+2]
val = get_val(ints, arg1, argmode[0])
if ((op == 5) and (val != 0)) or ((op == 6) and (val == 0)):
pos = get_val(ints, arg2, argmode[1])
else:
pos += 3
elif (op == 7) or (op == 8):
arg1 = ints[pos+1]
arg2 = ints[pos+2]
arg3 = ints[pos+3]
pos += 4
val1 = get_val(ints, arg1, argmode[0])
val2 = get_val(ints, arg2, argmode[1])
condition = ((op == 7) and (val1 < val2)) or ((op == 8) and (val1 == val2))
ints[arg3] = 1 if condition else 0
elif op == 99:
break
else:
print("Unknown opcode \"{}\"".format(ints[pos]), file=sys.stderr)
exit(1)
return ints
if __name__ == "__main__":
for line in sys.stdin:
ints = list(map(lambda x: int(x), line.split(',')))
run(ints, [5])