Solution to problem 5 part 1
This commit is contained in:
parent
574e1667f8
commit
53812f85a7
@ -56,11 +56,52 @@
|
||||
# Consider only horizontal and vertical lines. At how many points do at least
|
||||
# two lines overlap?
|
||||
|
||||
with open("files/P5.txt", "r") as f:
|
||||
from collections import defaultdict
|
||||
from typing import DefaultDict, Tuple
|
||||
|
||||
with open("files/P5.txt") as f:
|
||||
points = [
|
||||
points
|
||||
for line in f.read().strip().split("\n")
|
||||
for points in line.split(" -> ")
|
||||
]
|
||||
p1 = points[::2]
|
||||
p2 = points[1::2]
|
||||
|
||||
|
||||
point_1 = points[::2]
|
||||
x1y1 = [int(val) for p in point_1 for val in p.split(",")]
|
||||
x_1 = x1y1[::2]
|
||||
y_1 = x1y1[1::2]
|
||||
|
||||
point_2 = points[1::2]
|
||||
x2y2 = [int(val) for p in point_2 for val in p.split(",")]
|
||||
x_2 = x2y2[::2]
|
||||
y_2 = x2y2[1::2]
|
||||
|
||||
|
||||
def get_range(p1: int, p2: int) -> Tuple[int, int, int]:
|
||||
if p1 > p2:
|
||||
step = -1
|
||||
p2 -= 1
|
||||
else:
|
||||
step = 1
|
||||
p2 += 1
|
||||
return p1, p2, step
|
||||
|
||||
|
||||
def part_1() -> None:
|
||||
grid: DefaultDict[Tuple[int, int], int] = defaultdict(int)
|
||||
for idx in range(len(points) // 2):
|
||||
if x_1[idx] == x_2[idx]:
|
||||
start, stop, step = get_range(y_1[idx], y_2[idx])
|
||||
for pos in range(start, stop, step):
|
||||
grid[x_1[idx], pos] += 1
|
||||
elif y_1[idx] == y_2[idx]:
|
||||
start, stop, step = get_range(x_1[idx], x_2[idx])
|
||||
for pos in range(start, stop, step):
|
||||
grid[pos, y_1[idx]] += 1
|
||||
|
||||
print(sum(1 for key in grid.values() if key > 1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
part_1()
|
||||
|
Loading…
Reference in New Issue
Block a user