-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathintcode.py
More file actions
135 lines (128 loc) · 3.36 KB
/
Copy pathintcode.py
File metadata and controls
135 lines (128 loc) · 3.36 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
from collections import defaultdict
def parse(input):
prog = defaultdict(lambda:0)
for i,v in enumerate(input.split(',')):
prog[i] = int(v)
return prog
TRACE = 0
def run(mem):
i = 0
rel = 0
def get(j,m):
p = i+j
if m == 0:
p = mem[p]
elif m == 2:
p = mem[p] + rel
return p
while 1:
s = ('0000'+str(mem[i]))[-5:]
a,b,c,op = int(s[0]), int(s[1]), int(s[2]), int(s[3:])
if op == 1:
x = get(1,c)
y = get(2,b)
p = get(3,a)
if TRACE: print(f'{i}: {mem[x]}+{mem[y]}={mem[x] + mem[y]} => {p} ({mem[p]})')
mem[p] = mem[x] + mem[y]
i += 4
elif op == 2:
x = get(1,c)
y = get(2,b)
p = get(3,a)
if TRACE: print(f'{i}: {mem[x]}*{mem[y]}={mem[x] * mem[y]} => {p} ({mem[p]})')
mem[p] = mem[x] * mem[y]
i += 4
elif op == 3:
p = get(1,c)
if TRACE: print(f'{i}: request ? => {p}')
mem[p] = yield
if TRACE: print(f'{i}: store {mem[p]} => {p}')
i += 2
elif op == 4:
p = get(1,c)
if TRACE: print(f'{i}: out {mem[p]} <- {p}')
yield mem[p]
i += 2
elif op == 5:
x = get(1,c)
y = get(2,b)
if TRACE: print(f'{i}: if ({mem[x]} @ {x}) jump {mem[y]} @ {y}')
if mem[x]:
i = mem[y]
else:
i += 3
elif op == 6:
x = get(1,c)
y = get(2,b)
if TRACE: print(f'{i}: if not ({mem[x]} @ {x}) jump {mem[y]} @ {y}')
if not mem[x]:
i = mem[y]
else:
i += 3
elif op == 7:
x = get(1,c)
y = get(2,b)
p = get(3,a)
if TRACE: print(f'{i}: {mem[x]} < {mem[y]} => {p}')
mem[p] = int(mem[x] < mem[y])
i += 4
elif op == 8:
x = get(1,c)
y = get(2,b)
p = get(3,a)
if TRACE: print(f'{i}: {mem[x]} == {mem[y]} => {p}')
mem[p] = int(mem[x] == mem[y])
i += 4
elif op == 9:
x = get(1,c)
if TRACE: print(f'{i}: rel = {rel} + {mem[x]}')
rel += mem[x]
i += 2
elif op == 99:
return
else:
raise Exception('Unknown opcode', op)
break
def readASCII(proc):
s = ''
try:
q = next(proc)
while q!=None:
if s==10:
print(s)
s = ''
else:
s += chr(q)
q = next(proc)
except StopIteration:
print('stopped')
pass
if len(s)>0:
print(s)
s = ''
return q
def sendASCII(proc, txt):
print(txt)
out = ''
s = ''
try:
for c in txt:
q = proc.send(ord(c))
while q!=None:
out += chr(q)
if q==10:
print(s)
s = ''
else:
if q>0x110000:
print('got number', q)
else:
s += chr(q)
q = next(proc)
except StopIteration:
print('stopped')
pass
if len(s)>0:
print(s)
s = ''
return q or out