Advent of Code 2021 Python Solution: Day 5

qviper

Viper

Posted on December 5, 2021

Advent of Code 2021 Python Solution: Day 5

Day 5

Here is the problem link.

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

masked = coordinates[m]  
for co in masked:    
    for x in range(min(co[0], co[2]), max(co[0], co[2])+1):
        for y in range(min(co[1], co[3]), max(co[1], co[3])+1):
            board[x, y] += 1
print((board.flatten()>1).sum())    
Enter fullscreen mode Exit fullscreen mode

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
masked = coordinates[m]

for co in masked:
    # add or sub to x1?
    dx = int(co[2]>co[0]) or -1
    dy = int(co[3]>co[1]) or -1

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

print((board.flatten()>1).sum())    
Enter fullscreen mode Exit fullscreen mode

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

Why not read more?

💖 💪 🙅 🚩
qviper
Viper

Posted on December 5, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Advent of Code 2021 Python Solution: Day 16
adventofcode Advent of Code 2021 Python Solution: Day 16

December 17, 2021

Advent of Code 2021 Python Solution: Day 15
adventofcode Advent of Code 2021 Python Solution: Day 15

December 15, 2021

Advent of Code 2021 Python Solution: Day 14
adventofcode Advent of Code 2021 Python Solution: Day 14

December 14, 2021

Advent of Code 2021 Python Solution: Day 13
adventofcode Advent of Code 2021 Python Solution: Day 13

December 13, 2021

Advent of Code 2021 Python Solution: Day 12
adventofcode Advent of Code 2021 Python Solution: Day 12

December 12, 2021