view the Advent of Code 2021 Day 7 challenge
# Setup - load any packages
import numpy as np
def LoadData(filename):
return np.loadtxt(filename, dtype='int', delimiter=',')
day7_raw=LoadData('day7_data.txt')
def CalculatePart2Fuel(distance):
return int((distance*(distance+1))/2)
def CalculateFuel(positions, new_location, Part1):
# variable to store the fuel needed
fuel=0
#loop through each position and caluclate the cost to move it to the new location
for location in positions:
# calculate distance between current and new location
distance = abs(location - new_location)
if Part1==True:
fuel=fuel + distance
else:
# Calculate increased fuel cost
fuel=fuel + CalculatePart2Fuel(distance)
# return the fuel calculation
return fuel
def CalculateBestPosition(positions, Part1=True):
# Set default best fuel value
best_fuel=999999999
#loop through each possible value between min and max position
for i in range(positions.min(), positions.max()+1):
temp_fuel=CalculateFuel(positions, i, Part1)
if temp_fuel< best_fuel:
best_fuel=temp_fuel
return best_fuel
p1_answer=CalculateBestPosition(day7_raw)
print(f'answer = {p1_answer}')
answer = 356179
p2_answer=CalculateBestPosition(day7_raw, False)
print(f'answer = {p2_answer}')
answer = 99788435