-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaoc202105.py
91 lines (67 loc) · 2.15 KB
/
aoc202105.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
"""AoC 5, 2021: Hydrothermal Venture."""
# Standard library imports
import collections
import itertools
import pathlib
import sys
def parse_data(puzzle_input):
"""Parse input."""
return [
[int(xy) for points in line.split(" -> ") for xy in points.split(",")]
for line in puzzle_input.split("\n")
]
def part1(data):
"""Solve part 1."""
return count_overlaps(
(x1, y1, x2, y2) for x1, y1, x2, y2 in data if x1 == x2 or y1 == y2
)
def part2(data):
"""Solve part 2."""
return count_overlaps(data)
def count_overlaps(lines):
"""Count overlaps between a list of lines.
## Example:
>>> count_overlaps([[3, 3, 6, 6], [3, 3, 6, 3], [6, 6, 6, 3]])
3
"""
overlaps = collections.Counter(point for line in lines for point in points(line))
return sum(num_overlaps >= 2 for num_overlaps in overlaps.values())
def points(line):
"""List all points making up a line.
## Examples:
>>> list(points([0, 3, 3, 3]))
[(0, 3), (1, 3), (2, 3), (3, 3)]
>>> list(points([3, 3, 3, 0]))
[(3, 3), (3, 2), (3, 1), (3, 0)]
>>> list(points([1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
"""
x1, y1, x2, y2 = line
yield from ((x, y) for x, y in zip(coords(x1, x2), coords(y1, y2)))
def coords(start, stop):
"""List coordinates between start and stop, inclusive.
If start and stop are equal, then return the coordinate infinitely.
## Examples:
>>> list(coords(0, 3))
[0, 1, 2, 3]
>>> list(coords(2, -2))
[2, 1, 0, -1, -2]
>>> list(itertools.islice(coords(3, 3), 6))
[3, 3, 3, 3, 3, 3]
"""
if start < stop:
yield from range(start, stop + 1)
elif start > stop:
yield from range(start, stop - 1, -1)
else:
yield from itertools.repeat(start)
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().strip())
print("\n".join(str(solution) for solution in solutions))