view the Advent of Code 2021 Day 5 challenge
# Setup - load any packages
import pandas as pd
import numpy as np
#read the data into a pandas dataframe
def LoadData(filename):
return pd.read_csv(filename,
#seperators are " -> " or ","
sep=" -> |,",
names=['x1', 'y1', 'x2', 'y2'],
header=None,
engine="python")
def CreateGrid(x,y):
return np.zeros((x,y), dtype=int)
# load the data
day5_lines=LoadData("day5_data.txt")
# get the minimum and maximum values
print(f'min = {day5_lines.min().min()} max = {day5_lines.max().max()}')
min = 10 max = 989
def MapVents (data, grid, part1=True):
#loop through each row in the
for index, row in data.iterrows():
if HoriOrVert(row):
#process
grid=PlotLine(row, grid)
else:
#process all lines
if part1==False:
grid=PlotDiagonalLine(row, grid)
#Calculate the total number of overlaping cells
count=CountOverlaps(grid)
#return the result
return count
def HoriOrVert(row):
#Return true if the line is horizontal or vertical i.e X1/2 or Y1/2 values are the same
if row["x1"]==row["x2"] or row["y1"]==row["y2"] :
return True
else:
return False
def CountOverlaps(grid):
# Count the number of values greater than 1
return sum(sum(grid>1))
def PlotLine(row, grid):
# Add the line to the grid
for i in range(min(row["x1"], row["x2"]),max(row["x1"],row["x2"])+1):
for c in range(min(row["y1"], row["y2"]),max(row["y1"],row["y2"])+1):
grid[i][c]=grid[i][c]+1
# Return the updated grid
return grid
def PlotDiagonalLine(row, grid):
# determine the direction
if (((row["x1"] < row["x2"]) and (row["y1"] < row["y2"]) or (row["x1"] > row["x2"]) and (row["y1"] > row["y2"]))):
#diagonal up
#Set starting x and y values
x=min(row["x1"], row["x2"])
y=min(row["y1"], row["y2"])
for i in range((max(row["x1"],row["x2"])-min(row["x1"], row["x2"]))+1):
# increase the cell value by 1
grid[x][y]=grid[x][y]+1
# increase x and y coordinates
x = x + 1
y = y + 1
else:
# diagonal down
# Set starting x and y values
x=min(row["x1"], row["x2"])
# use maximum for diagonal downward lines
y=max(row["y1"], row["y2"])
for i in range((max(row["x1"],row["x2"])-min(row["x1"], row["x2"]))+1):
# increase the cell value by 1
grid[x][y]=grid[x][y]+1
# increase x and decrease y coordinates
x = x + 1
y = y - 1
# Return the updated grid
return grid
# load the data
day5_lines=LoadData("day5_data.txt")
# get the minimum and maximum values
print(f'min = {day5_lines.min().min()} max = {day5_lines.max().max()}')
# create a 1000x1000 numpy array to store the lines
grid=CreateGrid(1000,1000)
p1_answer=MapVents(day5_lines, grid, True)
print(f'answer = {p1_answer}')
min = 10 max = 989 answer = 5698
# load the data
day5_lines=LoadData("day5_data.txt")
# get the minimum and maximum values
print(f'min = {day5_lines.min().min()} max = {day5_lines.max().max()}')
# create a 1000x1000 numpy array to store the lines
grid=CreateGrid(1000,1000)
p2_answer=MapVents(day5_lines, grid, False)
print(f'answer = {p2_answer}')
min = 10 max = 989 answer = 15463