-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaoc201910.py
100 lines (76 loc) · 2.65 KB
/
aoc201910.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
"""AoC 10, 2019: Monitoring Station."""
# Standard library imports
import collections
import math
import pathlib
import sys
# Third party imports
from codetiming import Timer
def parse_data(puzzle_input):
"""Parse input."""
grid = {
(row, col)
for row, line in enumerate(puzzle_input.split("\n"))
for col, char in enumerate(line)
if char == "#"
}
return [(count_los(grid, row, col), row, col) for row, col in grid]
def part1(stations):
"""Solve part 1."""
return max(stations)[0]
def part2(stations):
"""Solve part 2."""
_, row, col = max(stations)
grid = {(row, col) for _, row, col in stations}
asteroids = sort_by_angle(grid, row, col)
vrow, vcol = vaporize(asteroids, row, col)
return vrow + vcol * 100
def count_los(grid, row, col):
"""Count the number of asteroids in line-of-sight from the given position."""
return sum(in_sight(grid, row, col, to_row, to_col) for to_row, to_col in grid)
def in_sight(grid, row, col, to_row, to_col):
"""Check if (to_row, to_col) is in line-of-sight from (row, col)."""
if to_row == row and to_col == col:
return False
drow, dcol = to_row - row, to_col - col
num_steps = math.gcd(drow, dcol)
step_row, step_col = drow / num_steps, dcol / num_steps
return all(
(row + step * step_row, col + step * step_col) not in grid
for step in range(1, num_steps)
)
def sort_by_angle(grid, row, col):
"""Sort asteroids by angle, as seen from (row, col)."""
return sorted(
(
math.atan2(c - col, row - r) % (2 * math.pi),
-abs(r - row) + -abs(c - col),
r,
c,
)
for r, c in grid - {(row, col)}
)
def vaporize(asteroids, row, col, number=200):
"""Vaporize asteroids in order."""
number = min(len(asteroids), number)
queue = collections.deque(asteroids)
grid = {(row, col) for _, _, row, col in asteroids}
num_vaporized = 0
while num_vaporized < number:
angle, distance, to_row, to_col = queue.popleft()
if in_sight(grid, row, col, to_row, to_col):
grid -= {(to_row, to_col)}
num_vaporized += 1
else:
queue.append((angle, distance, to_row, to_col))
return to_row, to_col
def solve(puzzle_input):
"""Solve the puzzle for the given input."""
data = parse_data(puzzle_input)
yield part1(data)
yield part2(data)
if __name__ == "__main__":
for path in sys.argv[1:]:
print(f"\n{path}:")
solutions = solve(puzzle_input=pathlib.Path(path).read_text().rstrip())
print("\n".join(str(solution) for solution in solutions))