Day 5, Year 2021: Hydrothermal Venture
First read the problem description.
import numpy as np
def new_grid(n):
return np.zeros((n,n), np.int64)
def parse_points(seg):
= seg.rstrip().split(' -> ')
start, end = map(int, start.split(','))
x1, y1 = map(int, end.split(','))
x2, y2 return x1, y1, x2, y2
def slice_range(x1, y1, x2, y2):
if y1 > y2:
= range(y1, y2-1, -1)
y else:
= range(y1, y2+1)
y
if x1 > x2:
= range(x1, x2-1, -1)
x else:
= range(x1, x2+1)
x
return (y, x)
def grid_slice(grid, seg, diagonal):
= parse_points(seg)
x1, y1, x2, y2 if y1 == y2 or x1 == x2 or diagonal:
return slice_range(x1, y1, x2, y2)
else:
return None
def overlapping(grid, f, diagonal=False):
for l in f.splitlines():
= grid_slice(grid, l, diagonal)
s if s is not None:
+= 1
grid[s] return np.sum(grid >= 2)
= new_grid(10)
g = """0,9 -> 5,9
test 8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2"""
assert overlapping(g, test) == 5
= new_grid(10)
g assert overlapping(g, test, diagonal=True) == 12
import import_ipynb
import helper
= helper.read_file('2021_5.txt')
f = new_grid(1000)
g overlapping(g, f)
5280
= new_grid(1000)
g =True) overlapping(g, f, diagonal
16716
Source code of the solution(s):