-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-3.py
executable file
·350 lines (285 loc) · 11.1 KB
/
day-3.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
#!/usr/bin/env python
"""Advent of Code Programming Puzzles
2019 Edition - Day Three
Puzzle Solution in Python
"""
import argparse
import logging
import operator
import os
import sys
from typing import Iterator
log = logging.getLogger(__name__)
# Common Methods ---------------------------------------------------------------
def convert_token(token: str) -> tuple[int, int]:
"""Converts string token into 2d grid offset
:param token: token in string format
:return: 2d grid offset in integer format
"""
direction, length = token[:1], int(token[1:])
assert direction in ['R', 'L', 'U', 'D']
if direction in ['L', 'D']:
length *= -1
offset = (length, 0) if direction in ['R', 'L'] else (0, length)
return offset
def load_contents(filename: str) -> list[list[tuple[int, int]]]:
"""Load contents from the given file
:param filename: filename as string
:return: converted contents
"""
wires = list(open(filename).read().strip().split(os.linesep))
log.info(f'Loaded {len(wires)} wires from {filename}')
assert 0 == len(wires) % 2
contents = [[convert_token(t) for t in w.split(',')] for w in wires]
return contents
def enumerate_corners(wire: list[tuple[int, int]]) -> Iterator[tuple[int, int]]:
"""Enumerate corners for the given wire path
:param wire: list of segments for a given wire
:yield: location of segment corner
"""
corner = (0, 0)
for offset in wire:
corner = tuple(map(operator.add, corner, offset))
yield corner
def enumerate_segments(wire: list[tuple[int, int]]) \
-> Iterator[tuple[tuple[int, int]]]:
"""Enumerates segments out of a given wire path
:param wire: list of segments for a given wire
:yield: segments extremities
"""
last_corner = (0, 0)
for offset in wire:
corner = tuple(map(operator.add, last_corner, offset))
yield tuple([last_corner, corner])
last_corner = corner
# def measure_distance(segment: tuple[tuple[int, int]]) -> float:
# """
#
# :param segment:
# :return:
# """
# a, b = segment[0:2]
# px = b[0] - a[0]
# py = b[1] - a[1]
# norm = px * px + py * py
# u = (-a[0] * px - a[1] * py) / float(norm)
# u = min(1, max(u, 0))
# x = a[0] + u * px
# y = a[1] + u * py
# dist = (x * x + y * y)
# return dist
def measure_manhattan_distance(segment: tuple[tuple[int, int]]) -> int:
"""Measure the manhattan distance between a segment and the central port
:param segment: pair of coordinates
:return: manhattan distance
"""
a, b = segment[0:2]
if a[0] == b[0]:
distance = abs(a[0])
if (a[1] < 0) != (b[1] < 0): # different sign
return distance
else:
distance += abs(min([a[1], b[1]]))
return distance
else:
distance = abs(a[1])
if (a[0] < 0) != (b[0] < 0): # different sign
return distance
else:
distance += abs(min([a[0], b[0]]))
return distance
def sort_closest_central(segments: list[tuple[tuple[int, int]]]) \
-> list[tuple[tuple[int, int]]]:
"""Sort segments with the ones that are closest to the central port first
:param segments: list of segments with extremities points
:return: sorted list of segments with extremities points
"""
sorted_segments = sorted(
segments, key=lambda s: measure_manhattan_distance(s))
return sorted_segments
def intersects(segments: tuple[tuple[tuple[int, int]]]) -> bool:
"""Test if the given segments intersect
:param segments: pair of segments
:return: true if both segments intersect
"""
if min([segments[0][0][0], segments[0][1][0]]) >= \
max([segments[1][0][0], segments[1][1][0]]):
return False
if max([segments[0][0][0], segments[0][1][0]]) <= \
min([segments[1][0][0], segments[1][1][0]]):
return False
if min([segments[0][0][1], segments[0][1][1]]) >= \
max([segments[1][0][1], segments[1][1][1]]):
return False
if max([segments[0][0][1], segments[0][1][1]]) <= \
min([segments[1][0][1], segments[1][1][1]]):
return False
return True
def intersect_location(segments: tuple[tuple[tuple[int, int]]]) \
-> tuple[int, int]:
"""Return the location where segments intersect
:param segments: pair of segments
:return: true if both segments intersect
"""
if segments[0][0][0] == segments[0][1][0]:
return segments[0][0][0], segments[1][0][1]
else:
return segments[1][0][0], segments[0][0][1]
def crosses(segment: tuple[tuple[int, int]], location: tuple[int, int]) -> bool:
"""Check if a segment crosses a location
:param segment: segment
:param location: grid coordinates
:return: true if the location is on the segment
"""
x, y = location
ax, ay = segment[0]
bx, by = segment[1]
if ax == bx == x and min(ay, by) < y < max(ay, by):
return True
if ay == by == y and min(ax, bx) < x < max(ax, bx):
return True
return False
def measure_length(segment: tuple[tuple[int, int]]) -> int:
"""Measure length of the given segment
:param segment: segment
:return: segment length
"""
length = 0
length += abs(segment[1][0] - segment[0][0])
length += abs(segment[1][1] - segment[0][1])
return length
def measure_distance(segment: tuple[tuple[int, int]],
location: tuple[int, int]) -> int:
"""Measure distance between start of segment and a location
:param segment: segment
:param location: location
:return: distance between start of segment and a location
"""
length = 0
length += abs(location[0] - segment[0][0])
length += abs(location[1] - segment[0][1])
return length
# Solving Methods --------------------------------------------------------------
def solve(contents: list[list[tuple[int, int]]]) -> int:
"""Solve the first part of the puzzle
:param contents: list of offsets per wire
:return: answer of the puzzle
"""
segments_by_orientation = {
'horizontal': [],
'vertical': []
}
for wire in contents[0:2]:
segments = list(enumerate_segments(wire=wire))
even_segments = [s for i, s in enumerate(segments) if 0 == i % 2]
odd_segments = [s for i, s in enumerate(segments) if 1 == i % 2]
even_are_vertical = even_segments[0][0][0] == even_segments[0][1][0]
horizontal = odd_segments if even_are_vertical else even_segments
vertical = even_segments if even_are_vertical else odd_segments
segments_by_orientation['horizontal'].append(horizontal)
segments_by_orientation['vertical'].append(vertical)
intersection_distances = []
for i, hgroud in enumerate(segments_by_orientation['horizontal']):
for sh in hgroud:
vgroup = segments_by_orientation['vertical'][1 - i]
for sv in vgroup:
if intersects((sh, sv)):
intersection_distances.append(
sum(map(abs, intersect_location((sh, sv)))))
log.debug('intersect: '
f'{intersect_location((sh, sv))}, {sh}, {sv}')
answer = min(intersection_distances)
return answer
def solve_part_two(contents: list[list[tuple[int, int]]]) -> int:
"""Solve the second part of the puzzle
:param contents: list of offsets per wire
:return: answer of the puzzle
"""
segments_by_orientation = {
'horizontal': [],
'vertical': []
}
for wire in contents[0:2]:
segments = list(enumerate_segments(wire=wire))
even_segments = [s for i, s in enumerate(segments) if 0 == i % 2]
odd_segments = [s for i, s in enumerate(segments) if 1 == i % 2]
even_are_vertical = even_segments[0][0][0] == even_segments[0][1][0]
horizontal = odd_segments if even_are_vertical else even_segments
vertical = even_segments if even_are_vertical else odd_segments
segments_by_orientation['horizontal'].append(horizontal)
segments_by_orientation['vertical'].append(vertical)
intersections = dict()
for i, hgroud in enumerate(segments_by_orientation['horizontal']):
for sh in hgroud:
vgroup = segments_by_orientation['vertical'][1 - i]
for sv in vgroup:
if intersects((sh, sv)):
intersections[intersect_location((sh, sv))] = (sh, sv)
log.debug('intersect: '
f'{intersect_location((sh, sv))}, {sh}, {sv}')
log.debug(f'Found {len(intersections)} intersections')
segments_per_wires = [list(enumerate_segments(wire=w))
for w in contents[0:2]]
combined_steps_list = list()
for location, intersect_segments in intersections.items():
combined_steps = 0
for segments in segments_per_wires:
for segment in segments:
if not crosses(segment=segment, location=location):
combined_steps += measure_length(segment=segment)
else:
combined_steps += measure_distance(
segment=segment, location=location)
break
combined_steps_list.append(combined_steps)
answer = min(combined_steps_list)
return answer
# Support Methods --------------------------------------------------------------
EXIT_SUCCESS = 0
LOG_FORMAT = ('%(asctime)s - %(levelname)s - %(module)s - '
'%(funcName)s - %(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)
answer = solve(contents=contents)
print(answer)
if compute_part_two:
contents = load_contents(filename=args.filename)
answer = solve_part_two(contents=contents)
print(answer)
return EXIT_SUCCESS
if __name__ == "__main__":
sys.exit(main())