-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-7.py
330 lines (278 loc) · 10.6 KB
/
day-7.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
#!/usr/bin/env python
"""Advent of Code Programming Puzzles
2019 Edition - Day 7
Puzzle Solution in Python
"""
import argparse
import itertools
import logging
import operator
import os
import sys
from enum import IntEnum
from functools import reduce
log = logging.getLogger(__name__)
# Intcode Common Methods -------------------------------------------------------
def load_contents(filename: str) -> list[list[int]]:
"""Load and convert contents from file
:param filename: input filename
:return: list of integer lists with variable length
"""
lines = open(filename).read().strip().split(os.linesep)
contents = [list(map(int, l.split(','))) for l in lines]
log.info(f'Loaded {len(contents)} lists from {filename}, '
f'with a total of {sum(len(l) for l in contents)} instructions')
return contents
class Intcode(IntEnum):
ADD = 1
MUL = 2
RD = 3
WR = 4
JNZ = 5
JZ = 6
ALT = 7
AE = 8
HALT = 99
class ParameterMode(IntEnum):
POSITION_MODE = 0
IMMEDIATE_MODE = 1
opcode_map = {
Intcode.ADD: {'parameters': 2},
Intcode.MUL: {'parameters': 2},
Intcode.RD: {'parameters': 0},
Intcode.WR: {'parameters': 1},
Intcode.JNZ: {'parameters': 2},
Intcode.JZ: {'parameters': 2},
Intcode.ALT: {'parameters': 2},
Intcode.AE: {'parameters': 2},
Intcode.HALT: {'parameters': 0},
}
MAX_PARAMETERS = max(opcode['parameters'] for opcode in opcode_map.values())
def decode_instruction(instruction: int) -> [int, list[int]]:
"""Decode instruction into opcode and parameter modes
:param instruction: instruction
:return: opcode and list of parameter modes
"""
digits = list(map(int, str(instruction)))
opcode = int(''.join(map(str, digits[-2:])))
parameters = opcode_map[opcode]['parameters']
modes = list(reversed(digits[:-2])) + [0] * (parameters - max(0, len(digits) - 2))
return opcode, modes
def fetch_arguments(data: list[int], opcode_ptr: int,
parameter_modes: list[int]) -> list[int]:
"""Fetch arguments from Intcode data
:param data: list of Intcode instructions
:param opcode_ptr: opcode to be executed
:param parameter_modes: opcode arguments parameter modes
:return: opcode argument values
"""
arguments = list()
for i, parameter_mode in enumerate(parameter_modes):
argument_address = opcode_ptr + 1 + i
assert parameter_mode in ParameterMode.__members__.values()
if parameter_mode == ParameterMode.POSITION_MODE:
argument_ptr = data[argument_address]
argument = data[argument_ptr]
elif parameter_mode == ParameterMode.IMMEDIATE_MODE:
argument = data[argument_address]
else:
raise Exception
arguments.append(argument)
return arguments
def execute_opcode(data: list[int], opcode_ptr: int,
inputs: list[int]) -> [int, list[int], any]:
"""Execute the pointed instruction
:param data: list of Intcode instructions
:param opcode_ptr: opcode to be executed
:param inputs: input value stack
:return: next opcode pointer, updated input stack, output value or nothing
"""
instruction = data[opcode_ptr]
opcode, parameter_modes = decode_instruction(instruction)
assert Intcode(opcode) in opcode_map
opcode_args = fetch_arguments(data=data, opcode_ptr=opcode_ptr,
parameter_modes=parameter_modes)
output = None
if opcode == Intcode.ADD:
output_ptr = data[opcode_ptr + opcode_map[opcode]['parameters'] + 1]
output_value = sum(opcode_args)
data[output_ptr] = output_value
opcode_ptr += opcode_map[opcode]['parameters'] + 2
elif opcode == Intcode.MUL:
output_ptr = data[opcode_ptr + opcode_map[opcode]['parameters'] + 1]
output_value = reduce(operator.mul, opcode_args, 1)
data[output_ptr] = output_value
opcode_ptr += opcode_map[opcode]['parameters'] + 2
elif opcode == Intcode.RD:
output_ptr = data[opcode_ptr + opcode_map[opcode]['parameters'] + 1]
output_value = inputs.pop(0)
data[output_ptr] = output_value
opcode_ptr += opcode_map[opcode]['parameters'] + 2
elif opcode == Intcode.WR:
output = opcode_args[0]
opcode_ptr += opcode_map[opcode]['parameters'] + 1
elif opcode == Intcode.JNZ:
jump = 0 != opcode_args[0]
if jump:
opcode_ptr = opcode_args[1]
else:
opcode_ptr += opcode_map[opcode]['parameters'] + 1
elif opcode == Intcode.JZ:
jump = 0 == opcode_args[0]
if jump:
opcode_ptr = opcode_args[1]
else:
opcode_ptr += opcode_map[opcode]['parameters'] + 1
elif opcode == Intcode.ALT:
output_ptr = data[opcode_ptr + opcode_map[opcode]['parameters'] + 1]
less_than = opcode_args[0] < opcode_args[1]
if less_than:
output_value = 1
else:
output_value = 0
data[output_ptr] = output_value
opcode_ptr += opcode_map[opcode]['parameters'] + 2
elif opcode == Intcode.AE:
output_ptr = data[opcode_ptr + opcode_map[opcode]['parameters'] + 1]
equals = opcode_args[0] == opcode_args[1]
if equals:
output_value = 1
else:
output_value = 0
data[output_ptr] = output_value
opcode_ptr += opcode_map[opcode]['parameters'] + 2
elif opcode == Intcode.HALT:
raise Exception
return opcode_ptr, inputs, output
# Puzzle Solving Methods -------------------------------------------------------
AMPLIFIERS: int = 5
PHASE_RANGE: tuple = (0, 5)
PHASE_RANGE_PART_TWO: tuple = (5, 10)
def compute_output_signal(
data: list[int], input_: int, phase: int,
instruction_ptr: int = 0) -> [bool, int, int]:
"""Compute output signal value for an amplifier stage
:param data: list of Intcode instructions
:param input_: amplifier stage input value
:param phase: amplifier stage phase setting
:return: output value
"""
if instruction_ptr == 0:
inputs = [phase, input_]
else:
inputs = [input_]
opcode_ptr: int = instruction_ptr
output = None
while data[opcode_ptr] != Intcode.HALT:
opcode_ptr, inputs, output = execute_opcode(
data=data, opcode_ptr=opcode_ptr, inputs=inputs)
if output is not None:
return False, opcode_ptr, output
return True, opcode_ptr, output
def solve(contents: list[int]) -> int:
"""Solve part one of the puzzle
:param contents: list of integers
:return: answer for the part one of the puzzle
"""
amp_outputs = list()
phase_settings = itertools.permutations(
iterable=range(*PHASE_RANGE), r=AMPLIFIERS)
for phase_setting in phase_settings:
amp_input = 0
amp_output = 0
for amp in range(AMPLIFIERS):
amp_phase_setting = phase_setting[amp]
temp_contents = contents.copy()
halt, instruction_ptr, amp_output = compute_output_signal(
data=temp_contents, input_=amp_input,
phase=amp_phase_setting)
amp_input = amp_output
amp_outputs.append(amp_output)
answer = max(amp_outputs)
return answer
def solve_part_two(contents: list[int]) -> int:
"""Solve part two of the puzzle
:param contents: list of integers
:return: answer for the part two of the puzzle
"""
amp_outputs = list()
phase_settings = itertools.permutations(
iterable=range(*PHASE_RANGE_PART_TWO), r=AMPLIFIERS)
for phase_setting in phase_settings:
amp_input = 0
amp_output = 0
per_stage_software = [contents.copy() for _ in range(AMPLIFIERS)]
per_stage_instruction_ptr = [0 for _ in range(AMPLIFIERS)]
amp = 0
iter = 0
while True:
if iter > 5:
assert per_stage_software[amp] != 0
amp_phase_setting = phase_setting[amp]
halt, instruction_ptr, output = compute_output_signal(
data=per_stage_software[amp], input_=amp_input,
phase=amp_phase_setting, instruction_ptr=per_stage_instruction_ptr[amp])
log.debug(f'iter #{iter}, stage {amp}: iptr {instruction_ptr}, output {output}')
assert contents != per_stage_software[amp]
assert instruction_ptr != 0
if output is not None:
amp_output = output
per_stage_instruction_ptr[amp] = instruction_ptr
amp_input = amp_output
if halt and (amp == 4):
break
amp = (amp + 1) % AMPLIFIERS
iter += 1
amp_outputs.append(amp_output)
answer = max(amp_outputs)
return answer
# Support Methods --------------------------------------------------------------
EXIT_SUCCESS = 0
LOG_FORMAT = '# %(msecs)-3d - %(funcName)-32s - %(levelname)-8s - %(message)s'
def configure_logger(verbose: bool):
"""Configure logging
:param verbose: display debug and info messages
:return: nothing
"""
logger = logging.getLogger()
logger.handlers = []
stdout = logging.StreamHandler(sys.stdout)
stdout.setLevel(level=logging.WARNING)
stdout.setFormatter(logging.Formatter(LOG_FORMAT))
logger.addHandler(stdout)
if verbose:
stdout.setLevel(level=logging.DEBUG)
logger.setLevel(level=logging.DEBUG)
def parse_arguments() -> argparse.Namespace:
"""Parse arguments provided by the command-line
:return: list of decoded arguments
"""
parser = argparse.ArgumentParser(description=__doc__)
pa = parser.add_argument
pa('filename', type=str, help='input contents filename')
pa('-p', '--part', type=int, help='solve only the given part')
pa('-v', '--verbose', action='store_true', help='print extra messages')
arguments = parser.parse_args()
return arguments
def main() -> int:
"""Script main method
:return: script exit code returned to the shell
"""
args = parse_arguments()
configure_logger(verbose=args.verbose)
log.debug(f'Arguments: {args}')
compute_part_one = not args.part or 1 == args.part
compute_part_two = not args.part or 2 == args.part
if compute_part_one:
contents = load_contents(filename=args.filename)
for i, c in enumerate(contents):
answer = solve(contents=c)
print(f'part one: index {i}, answer: {answer}')
if compute_part_two:
contents = load_contents(filename=args.filename)
for i, c in enumerate(contents):
answer = solve_part_two(contents=c)
print(f'part two: index {i}, answer: {answer}')
return EXIT_SUCCESS
if __name__ == "__main__":
sys.exit(main())