Advent of Code: Day 7
On Day 7, we are attacked by a giant whale and thankfully a swarm of crabs come to the rescue. Each crab has its own submarine that it controls. (Don't ask me, I felt like it's going out of control too.)
Now each crab is determined by its horizontal position. The example input is 16,1,2,0,4,2,7,1,2,14
. Now the crabs need to move horizontally until they're at the same position. Each unit of horizontal movement costs one fuel. Your goal is to find the optimal position that costs the least fuel for all crabs. To submit your result, enter the total fuel.
For the example above, the optimal position is 2. And the total fuel needed is 37.
It's pretty straight-forward so my solution is quite simple:
def read(filename):
file = open(filename)
crabs = [int(i) for i in file.readline().split(',')]
return crabs
def solve(crabs):
fuels = []
for position in range(min(crabs), max(crabs) + 1):
# Calculate total fuel if all crabs move to this position
fuel = 0
for crab in crabs:
moves = abs(crab - position)
fuel += moves
fuels.append(fuel)
print(min(fuels))
crabs = read('input.txt')
solve(crabs)
Part 2 has a modification that makes the puzzle more interesting.
The cost to move each horizontal unit, instead of 1, is now increasing. This means step 1 takes 1 fuel, step 2 takes 2 fuel, and so on. So now our solution needs some adjustment:
def read(filename):
file = open(filename)
crabs = [int(i) for i in file.readline().split(',')]
return crabs
def solve(crabs):
fuels = []
for position in range(min(crabs), max(crabs) + 1):
# Calculate total fuel if all crabs move to this position
fuel = 0
for crab in crabs:
moves = abs(crab - position)
fuel += (moves + 1) * moves / 2
fuels.append(fuel)
print(min(fuels))
crabs = read('input.txt')
solve(crabs)
I mean, it's pretty fun to have crabs zeroing in to save you underwater, isn't it?