aoc/2021/05/05.py
2021-12-07 21:17:49 -06:00

53 lines
1.2 KiB
Python

with open("input.txt") as f:
vents = [
list(map(int, (x1, y1, x2, y2)))
for line in f.read().split('\n')
for start, end in [line.split(' -> ')]
for x1, y1 in [start.split(',')]
for x2, y2 in [end.split(',')]
]
def count_overlaps(vents, part):
d = {}
def mark(x,y,d):
if (x,y) in d:
d[(x,y)] += 1
else:
d[(x,y)] = 1
def dirange(start, end):
"""A directional, inclusive range."""
if start > end:
return range(start, end-1, -1)
else:
return range(start, end+1)
for vent in vents:
x1, y1, x2, y2 = vent
if x1 == x2: # horizontal line
x = x1 # either i1 or i2 can be used for i value
for y in dirange(y1, y2):
mark(x,y,d)
elif y1 == y2: # vertical line
y = y1 # either j1 or j2 can be used for j value
for x in dirange(x1, x2):
mark(x,y,d)
else: # diagonal line
if part == 1: # ignore diagonals for part 1 --
continue # "For now, only consider horizontal and vertical lines"
rx = dirange(x1,x2)
ry = dirange(y1,y2)
for x, y in zip(rx, ry):
mark(x,y,d)
overlaps = 0
for v in d.values():
if v > 1:
overlaps += 1
return overlaps
print(
count_overlaps(vents, part=1),
count_overlaps(vents, part=2)
)