Where's day 6 you ask? Well, I got part 1 working but part 2 will take a while. I tried the brute force solution for part 2 and saw my computer use 7 gigs of RAM. Worst part was that is was still going, so I decided to stop it and rework the solution. I am almost guessing there is some dynamic programming involved but who knows. I will try to get day 6 up tomorrow along with day 8 but we'll see.
For now, here is my solution for day 7.
if __name__ == "__main__":
with open("input.txt", "r") as f:
crab_positions = f.read().split("\n")[0].split(",")
crab_positions = sorted(list(map(int, crab_positions)))
best_fuel_cost = 100000000
best_altered_fuel_cost = 100000000
for i in range(len(crab_positions)):
current_alignment = i
fuel_cost = 0
altered_fuel_cost = 0
for pos in crab_positions:
n = abs(pos - current_alignment)
altered_fuel_cost += n * (n+1) / 2
fuel_cost += n
if fuel_cost < best_fuel_cost:
best_fuel_cost = fuel_cost
if altered_fuel_cost < best_altered_fuel_cost:
best_altered_fuel_cost = altered_fuel_cost
print(f"Answer for Part 1: {best_fuel_cost}")
print(f"Answer for Part 2: {best_altered_fuel_cost}")
I cheated and used the formula for the sum of n
numbers. Whenever I use this formula I always get reminded of Gauss who supposedly figured this formula out by himself, when he was a child.
And as always here is my GitHub link - https://github.com/Bukkaraya/AoC_2021/tree/main/day_7