-
Notifications
You must be signed in to change notification settings - Fork 0
/
day5-2.py
83 lines (60 loc) · 1.9 KB
/
day5-2.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
from typing import List
from dataclasses import dataclass
import re
input_pattern = re.compile("^([0-9]+),([0-9]+) -> ([0-9]+),([0-9]+)$")
@dataclass
class Point:
x: int
y: int
def __hash__(self):
return hash((self.x, self.y))
class Line:
def __init__(self, x1: int, y1: int, x2: int, y2: int):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.points: List[Point] = self._compute_points()
def _compute_points(self) -> List[Point]:
dy = abs(self.y2 - self.y1)
dx = abs(self.x2 - self.x1)
x_start = min(self.x1, self.x2)
x_end = max(self.x1, self.x2)
y_start = min(self.y1, self.y2)
y_end = max(self.y1, self.y2)
if dx == 0:
return [Point(x_start, y) for y in range(y_start, y_end + 1)]
elif dy == 0:
return [Point(x, y_start) for x in range(x_start, x_end + 1)]
else:
x_dir = 1 if self.x2 > self.x1 else -1
y_dir = 1 if self.y2 > self.y1 else -1
points = []
for i in range(dx + 1):
x = self.x1 + i * x_dir
y = self.y1 + i * y_dir
points.append(Point(x, y))
return points
def parse_input() -> List[Line]:
lines: List[Line] = []
with open("day5-1-input.txt") as file:
for file_line in file:
x1, y1, x2, y2 = [int(n) for n in input_pattern.match(file_line).groups()]
lines.append(Line(x1, y1, x2, y2))
return lines
def main():
lines = parse_input()
counter = dict()
for line in lines:
for point in line.points:
if point in counter:
counter[point] += 1
else:
counter[point] = 1
points = 0
for times in counter.values():
if times > 1:
points += 1
print(points)
if __name__ == "__main__":
main()