DEV Community is a community of 793,259 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Viper

Posted on • Updated on

Advent of Code 2021 Python Solution: Day 5

Day 5

Part 1

import numpy as np
data,data1 = get_data(day=5)

# get(x1, y1, x2, y2)
coordinates = []
for d in data:
x1, y1, x2, y2 = list(map(int, d.replace(" -> ", ",").split(",")))
coordinates.append((x1, y1, x2, y2))

coordinates = np.array(coordinates)
mxx,mxy = coordinates[[0, 2]].max(), coordinates[[1, 3]].max()

board = np.zeros((mxx*2, mxy*2))

# check only horizontal or vertical line
m1 = coordinates[:, 0]==coordinates[:, 2]
m2 = coordinates[:, 1]==coordinates[:, 3]
m = m1 | m2

for x in range(min(co, co), max(co, co)+1):
for y in range(min(co, co), max(co, co)+1):
board[x, y] += 1
print((board.flatten()>1).sum())

The output will be 5 for above code where test data was used. Should use data1 for real output.

Part 2

# diagonal line
m1 = coordinates[:, 0]!=coordinates[:, 2]
m2 = coordinates[:, 1]!=coordinates[:, 3]
m=m1*m2

# add or sub to x1?
dx = int(co>co) or -1
dy = int(co>co) or -1

for dp in range(abs(co-co)+1):
x = co+dx*dp
y = co+dy*dp
board[x,y]+=1

print((board.flatten()>1).sum())

The output of above code will be 12 for test data.