My Advent of Code solutions in Python.
kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code
python
1import fileinput
2from utils import parse_nums
3
4
5INF = 1e9
6POINTS = []
7
8for line in fileinput.input():
9 x, y, dx, dy = parse_nums(line)
10 POINTS.append([x, y, dx, dy])
11
12best_x = INF
13best_y = INF
14seconds = 0
15
16while True:
17 min_x = INF
18 max_x = -INF
19 min_y = INF
20 max_y = -INF
21
22 for i, (x, y, dx, dy) in enumerate(POINTS):
23 min_x = min(min_x, x)
24 max_x = max(max_x, x)
25 min_y = min(min_y, y)
26 max_y = max(max_y, y)
27
28 POINTS[i][0] += dx
29 POINTS[i][1] += dy
30
31 diff_x = max_x - min_x
32 diff_y = max_y - min_y
33
34 improved = False
35
36 if diff_x < best_x:
37 best_x = diff_x
38 improved = True
39 if diff_y < best_y:
40 best_y = diff_y
41 improved = True
42
43 if not improved:
44 break
45
46 seconds += 1
47
48# Reverse by 2 timesteps to reassemble message
49for i, (x, y, dx, dy) in enumerate(POINTS):
50 POINTS[i][0] -= dx * 2
51 POINTS[i][1] -= dy * 2
52
53
54points = {(x, y) for x, y, dx, dy in POINTS}
55xs, ys = zip(*points)
56min_x, max_x = sorted(xs)[0], sorted(xs)[-1]
57min_y, max_y = sorted(ys)[0], sorted(ys)[-1]
58
59for y in range(min_y, max_y + 1):
60 print ''.join('#' if (x, y) in points else '.' for x in range(min_x, max_x + 1))
61
62print "Seconds until the above message is formed:", seconds - 1