-
Notifications
You must be signed in to change notification settings - Fork 0
/
23.py
123 lines (111 loc) · 3.33 KB
/
23.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
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
from lib import *
input = read_input(2019, 23)
class IntCode:
def __init__(self, mem):
self.mem = {i: e for i, e in enumerate(mem)}
self.pc = 0
self.running = False
self.inp = []
self.out = []
self.rel = 0
def start(self):
self.running = True
self.cont()
def get_arg(self, i):
mode = self.mem[self.pc] // (10 ** (i + 1)) % 10
out = self.mem[self.pc + i]
if mode == 1:
return out
elif mode == 2:
out += self.rel
return self.mem.get(out, 0)
def write_arg(self, i, value):
mode = self.mem[self.pc] // (10 ** (i + 1)) % 10
pos = self.mem[self.pc + i]
assert mode != 1
if mode == 2:
pos += self.rel
self.mem[pos] = value
def cont(self):
while True:
opcode = self.mem[self.pc] % 100
if opcode == 1:
self.write_arg(3, self.get_arg(1) + self.get_arg(2))
self.pc += 4
elif opcode == 2:
self.write_arg(3, self.get_arg(1) * self.get_arg(2))
self.pc += 4
elif opcode == 3:
if not self.inp:
return
self.write_arg(1, self.inp.pop(0))
self.pc += 2
elif opcode == 4:
self.out.append(self.get_arg(1))
self.pc += 2
elif opcode == 5:
if self.get_arg(1):
self.pc = self.get_arg(2)
else:
self.pc += 3
elif opcode == 6:
if not self.get_arg(1):
self.pc = self.get_arg(2)
else:
self.pc += 3
elif opcode == 7:
self.write_arg(3, int(self.get_arg(1) < self.get_arg(2)))
self.pc += 4
elif opcode == 8:
self.write_arg(3, int(self.get_arg(1) == self.get_arg(2)))
self.pc += 4
elif opcode == 9:
self.rel += self.get_arg(1)
self.pc += 2
elif opcode == 99:
self.running = False
return
(*mem,) = map(int, input.split(","))
nodes = [IntCode(mem) for _ in range(50)]
for i, node in enumerate(nodes):
node.inp.append(i)
node.start()
while True:
for i, node in enumerate(nodes):
while node.out:
dest, x, y, *node.out = node.out
if dest == 255:
print(y)
exit()
nodes[dest].inp += [x, y]
node.inp.append(-1)
node.cont()
(*mem,) = map(int, input.split(","))
nodes = [IntCode(mem) for _ in range(50)]
nat = None
nat_history = set()
for i, node in enumerate(nodes):
node.inp.append(i)
node.start()
while True:
idle = True
for i, node in enumerate(nodes):
while node.out:
idle = False
dest, x, y, *node.out = node.out
if dest == 255:
nat = x, y
else:
nodes[dest].inp += [x, y]
if not node.inp:
node.inp.append(-1)
else:
idle = False
node.cont()
if idle and nat:
x, y = nat
nodes[0].inp += [x, y]
if y in nat_history:
print(y)
exit()
nat_history.add(y)