-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday7.py
374 lines (304 loc) · 11.8 KB
/
day7.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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import argparse
from itertools import permutations
parser = argparse.ArgumentParser(description="AoC day 7")
parser.add_argument("file", help="The file that should be sourced")
parser.add_argument("-p", "--phase", help="The part of the exercise that we are at", type=int, default=1)
parser.add_argument("-t", "--target", help="A target value being aimed for", type=int, default=0)
def main(argv):
print(f"test, {argv}")
infile = open(argv.file, "r")
allItems = []
for line in infile:
# do a line operation
if line:
allItems.append(line)
infile.close()
# commands require a little more processing
commands = []
for item in allItems:
numSet = str.split(item, ',')
for x in numSet:
commands.append(int(x))
if argv.phase == 1:
sol = solutionPt1(commands, [0,1,2,3,4])
print(f"\nBiggest output is {sol[0]} at {sol[1]}")
elif argv.phase == 2:
sol = solutionPt2(commands, [5,6,7,8,9])
print(f"\nBiggest output is {sol[0]} at {sol[1]}")
# Opcode 1 adds together numbers read from two positions and stores the result in a third position.
# The three integers immediately after the opcode tell you these three positions
# - the first two indicate the positions from which you should read the input values,
# and the third indicates the position at which the output should be stored.
# Opcode 2 works exactly like opcode 1, except it multiplies the two inputs instead of adding them.
# Again, the three integers after the opcode indicate where the inputs and outputs are, not their values.
# Opcode 3 takes a single integer as input and saves it to the address given by its only parameter.
# For example, the instruction 3,50 would take an input value and store it at address 50.
# Opcode 4 outputs the value of its only parameter.
# For example, the instruction 4,50 would output the value at address 50.
# Opcode 5 is jump-if-true: if the first parameter is non-zero,
# it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing.
# Opcode 6 is jump-if-false: if the first parameter is zero,
# it sets the instruction pointer to the value from the second parameter. Otherwise, it does nothing.
# Opcode 7 is less than: if the first parameter is less than the second parameter,
# it stores 1 in the position given by the third parameter. Otherwise, it stores 0.
# Opcode 8 is equals: if the first parameter is equal to the second parameter, it stores 1 in the position given by the third parameter. Otherwise, it stores 0.
# 99 means that the program is finished and should immediately halt.
class Computer:
# a 'none' input is a user input halt
def __init__(self, program, prog_input=None):
self.program_orig = program
self.input_counter = 0
self.output = []
self.inpipe = []
self.outpipe = []
self.cur_state = None
def reset(self):
self.input_counter = 0
self.output = []
self.input = [None]
self.cur_state = None
# for i in range(0, len(self.program_orig)):
# self.program[i] = self.program_orig[i]
def run(self, restart=True):
if self.cur_state is None or restart:
self.cur_state = progState()
self.cur_state.turing = self.program_orig
while self.cur_state.running:
self.cur_state = self._parseCodes(self.cur_state)
if self.cur_state.errored:
print(f"irregular execution at pointer {self.cur_state.progPointer}")
if self.cur_state.paused_for_input:
return self.cur_state.turing
return self.cur_state.turing
def is_running(self):
if self.cur_state is None:
return False
return self.cur_state.running
def insert_pipeline(self, thing):
self.inpipe = [int(thing)]
def read_pipeline(self):
if len(self.outpipe) > 0:
# print(f" popped {self.outpipe[-1]}")
return self.outpipe.pop()
else:
return None
def _getModes(self, number):
return int(int(number % 1000 / 100)), int(number % 10000 / 1000), int(number / 10000)
def _getOp(self, number):
return int(number % 100)
def _grow_mem(self, state, spot):
if spot > len(state.turing):
growth = spot - len(state.turing)
for i in range(0, growth + 1):
state.turing.append(0)
def _parseCodes(self, curState):
opd = curState.clone()
command = self._getOp(curState.turing[curState.progPointer])
# mode 0 positional, 1 immediate
mode = self._getModes(curState.turing[curState.progPointer])
# print(f"pointer at {curState.progPointer}")
# print(f"command is {command}")
# print(f"mode is {mode}")
# print(f"program is {curState.turing}")
# 0 address mode
# 1 immediate mode
# 2 relative (offset) mode
loc = 0
if command in [1, 2, 3, 4, 5, 6, 7, 8]:
if mode[0] == 0:
loc = opd.turing[opd.progPointer + 1]
elif mode[0] == 1:
loc = opd.progPointer + 1
elif mode[0] == 2:
loc = opd.relative_base + opd.turing[opd.progPointer + 1]
self._grow_mem(opd, loc)
paramA = opd.turing[loc]
loc = 0
if command in [1, 2, 5, 6, 7, 8]:
if mode[1] == 0:
loc = opd.turing[opd.progPointer + 2]
elif mode[1] == 1:
loc = opd.progPointer + 2
elif mode[1] == 2:
loc = opd.relative_base + opd.turing[opd.progPointer + 2]
self._grow_mem(opd, loc)
paramB = opd.turing[loc]
loc = 0
if command in [1, 2, 5, 6, 7, 8]:
if mode[2] == 0:
loc = opd.turing[opd.progPointer + 3]
elif mode[2] == 1:
opd.errored = True
opd.running = False
print("Illegal write mode *immediate*")
return opd
elif mode[2] == 2:
loc = opd.relative_base + opd.turing[opd.progPointer + 3]
self._grow_mem(opd, loc)
paramC_loc = loc
if command == 1:
# Add from first two positions, store in the third
opd.turing[paramC_loc] = paramA + paramB
opd.progPointer += 4
elif command == 2:
# Add from first two positions, store in the third
opd.turing[paramC_loc] = paramA * paramB
opd.progPointer += 4
elif command == 3:
# take input
if opd.paused_for_input:
opd.turing[opd.turing[opd.progPointer + 1]] = self.inpipe.pop()
opd.paused_for_input = False
else:
if len(self.inpipe) == 1:
opd.turing[opd.turing[opd.progPointer + 1]] = self.inpipe.pop()
opd.paused_for_input = False
else:
opd.paused_for_input = True
return opd
opd.progPointer += 2
elif command == 4:
# output to buffer
self.outpipe.insert(0, paramA)
opd.progPointer += 2
elif command == 5:
# first value not zero, set pointer to second val
opd.progPointer = paramB if paramA != 0 else opd.progPointer + 3
elif command == 6:
# first value zero, set pointer to second val
opd.progPointer = paramB if paramA == 0 else opd.progPointer + 3
elif command == 7:
# if first param is less than second, store 1 in third, otherwise 0
opd.turing[paramC_loc] = 1 if paramA < paramB else 0
opd.progPointer += 4
elif command == 8:
# if first param is equal to second, store 1 in third, otherwise 0
opd.turing[paramC_loc] = 1 if paramA == paramB else 0
opd.progPointer += 4
elif command == 9:
# add to the prog's relative base
opd.relative_base += paramA
opd.progPointer += 2
elif command == 99:
# halt
opd.running = False
# print("--FINISH--")
else:
# error
opd.running = False
opd.errored = True
return opd
class progState:
def __init__(self):
self.progPointer = 0
self.turing = []
self.running = True
self.errored = False
self.paused_for_input = False
self.relative_base = 0
def clone(self):
temp = progState()
temp.progPointer = self.progPointer
temp.running = self.running
temp.turing = self.turing.copy()
temp.paused_for_input = self.paused_for_input
temp.relative_base = self.relative_base
return temp
def digit_splitter(num, min_size=1):
sign = 1
digits = []
if num < 0:
sign = -1
num = abs(num)
place = 1
while num > place:
digits.append(int(num % (place * 10) / place) * sign)
place *= 10
while len(digits) < min_size:
digits.append(0)
digits.reverse()
return digits
def solutionPt2(items, phases):
phase_num = 0
biggest_out = 0
biggest_phase = []
flagged_output = 0
allComps = []
for i in range(0, 5):
comp = Computer(items.copy())
comp.pipe_mode = True
allComps.append(comp)
possibleSettings = permutations([5,6,7,8,9], 5)
for phase in possibleSettings:
phase_digit = 0
print(f"curPhase : {phase}")
# setup and firstrun with phases
for amp in allComps:
amp.reset()
amp.insert_pipeline(phase[phase_digit])
amp.run()
phase_digit += 1
# feedback run
cur_amp = 0
bus = 0
while allComps[-1].is_running():
allComps[cur_amp].insert_pipeline(bus)
allComps[cur_amp].run(restart=False)
bus = allComps[cur_amp].read_pipeline()
cur_amp += 1
cur_amp = cur_amp % len(allComps)
# print("*", end="", flush=True)
if bus > biggest_out:
print(f"winner: phase {phase} : value {bus}")
biggest_out = bus
biggest_phase = phase
# else:
# print(f"loser: {next_buffer}")
if phase_num % 10000 == 0:
print(f"{int(phase_num/10000)}", end="", flush=True)
# print("blah")
# print(phase_num)
phase_num += 1
print(f"tagged output {flagged_output}")
return biggest_out, biggest_phase
def solutionPt1(items, phases):
phase_num = 0
biggest_out = 0
biggest_phase = []
flagged_output = 0
allComps = []
for i in range(0, 5):
comp = Computer(items.copy())
comp.pipe_mode = True
allComps.append(comp)
possibleSettings = permutations(phases, 5)
for setting in possibleSettings:
digit = 0
for comp in allComps:
comp.reset()
comp.insert_pipeline(setting[digit])
comp.run(restart=True)
digit += 1
# phase = digit_splitter(1234, 5)
phase = setting
phase_digit = 0
buffer = 0
for amp in allComps:
amp.insert_pipeline(buffer)
amp.run(restart=False)
buffer = amp.read_pipeline()
phase_digit += 1
if buffer > biggest_out:
print(f"winner: phase {phase_num} : value {buffer}")
biggest_out = buffer
biggest_phase = phase
# else:
# print(f"loser: {next_buffer}")
if phase_num % 10000 == 0:
print(f"{int(phase_num/10000)}", end="", flush=True)
# print("blah")
# print(phase_num)
phase_num += 1
print(f"tagged output {flagged_output}")
return biggest_out, biggest_phase
main(parser.parse_args())