My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Update 2018/10 solution

+37 -45
+37 -45
2018/day10.py
··· 1 1 import fileinput 2 - from copy import deepcopy 3 - from itertools import count 4 - 5 2 from utils import parse_nums 6 3 4 + 7 5 INF = 1e9 6 + POINTS = [] 8 7 8 + for line in fileinput.input(): 9 + x, y, dx, dy = parse_nums(line) 10 + POINTS.append([x, y, dx, dy]) 9 11 10 - def simulate(points, seconds=None): 11 - best_x = INF 12 - best_y = INF 12 + best_x = INF 13 + best_y = INF 14 + seconds = 0 13 15 14 - if seconds: 15 - loop = range(seconds) 16 - else: 17 - loop = count() 18 - 19 - for tick in loop: 20 - min_x = INF 21 - max_x = -INF 22 - min_y = INF 23 - max_y = -INF 24 - 25 - for i, (x, y, dx, dy) in enumerate(points): 26 - min_x = min(min_x, x) 27 - max_x = max(max_x, x) 28 - min_y = min(min_y, y) 29 - max_y = max(max_y, y) 30 - 31 - points[i][0] += dx 32 - points[i][1] += dy 33 - 34 - diff_x = max_x - min_x 35 - diff_y = max_y - min_y 16 + while True: 17 + min_x = INF 18 + max_x = -INF 19 + min_y = INF 20 + max_y = -INF 36 21 37 - improved = False 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) 38 27 39 - if diff_x < best_x: 40 - best_x = diff_x 41 - improved = True 42 - if diff_y < best_y: 43 - best_y = diff_y 44 - improved = True 28 + POINTS[i][0] += dx 29 + POINTS[i][1] += dy 45 30 46 - if not improved: 47 - return tick - 1 31 + diff_x = max_x - min_x 32 + diff_y = max_y - min_y 48 33 34 + improved = False 49 35 50 - POINTS = [] 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 51 42 52 - for line in fileinput.input(): 53 - x, y, dx, dy = parse_nums(line) 54 - POINTS.append([x, y, dx, dy]) 43 + if not improved: 44 + break 55 45 46 + seconds += 1 56 47 57 - points = deepcopy(POINTS) 58 - seconds_to_message = simulate(points) 59 - simulate(POINTS, seconds=seconds_to_message) 48 + # Reverse by 2 timesteps to reassemble message 49 + for i, (x, y, dx, dy) in enumerate(POINTS): 50 + POINTS[i][0] -= dx * 2 51 + POINTS[i][1] -= dy * 2 60 52 61 53 62 54 points = {(x, y) for x, y, dx, dy in POINTS} ··· 67 59 for y in range(min_y, max_y + 1): 68 60 print ''.join('#' if (x, y) in points else '.' for x in range(min_x, max_x + 1)) 69 61 70 - print "Seconds until the above message is formed:", seconds_to_message 62 + print "Seconds until the above message is formed:", seconds - 1