A giant whale has decided your submarine is its next meal, and it's much faster than you are. There's nowhere to run!
Suddenly, a swarm of crabs (each in its own tiny submarine - it's too deep for them otherwise) zooms in to rescue you! They seem to be preparing to blast a hole in the ocean floor; sensors indicate a massive underground cave system just beyond where they're aiming!
The crab submarines all need to be aligned before they'll have enough power to blast a large enough hole for your submarine to get through. However, it doesn't look like they'll be aligned before the whale catches you! Maybe you can help?
There's one major catch - crab submarines can only move horizontally.
You quickly make a list of the horizontal position of each crab (your puzzle input). Crab submarines have limited fuel, so you need to find a way to make all of their horizontal positions match while requiring them to spend as little fuel as possible.
For example, consider the following horizontal positions:
16,1,2,0,4,2,7,1,2,14
This means there's a crab with horizontal position 16, a crab with horizontal position 1, and so on.
Each change of 1 step in horizontal position of a single crab costs 1 fuel. You could choose any horizontal position to align them all on, but the one that costs the least fuel is horizontal position 2:
Move from 16 to 2: 14 fuel
Move from 1 to 2: 1 fuel
Move from 2 to 2: 0 fuel
Move from 0 to 2: 2 fuel
Move from 4 to 2: 2 fuel
Move from 2 to 2: 0 fuel
Move from 7 to 2: 5 fuel
Move from 1 to 2: 1 fuel
Move from 2 to 2: 0 fuel
Move from 14 to 2: 12 fuel
This costs a total of 37 fuel. This is the cheapest possible outcome; more expensive outcomes include aligning at position 1 (41 fuel), position 3 (39 fuel), or position 10 (71 fuel).
Determine the horizontal position that the crabs can align to using the least fuel possible. How much fuel must they spend to align to that position?
# Python imports
from pathlib import Path
from typing import Callable, Dict, Iterable, List, Tuple
import numpy as np
# Paths to data
testpath = Path("day07_test.txt")
datapath = Path("day07_data.txt")
We can load the input, like yesterday, as a list/array of integers.
def load_input(fpath: Path) -> np.array:
"""Return list of crab horizontal positions
:param fpath: Path to data file
"""
with fpath.open("r") as ifh:
return np.array([int(_) for _ in ifh.read().strip().split(",")])
This is an optimisation problem, and we assume that the cost function is smooth and well-behaved with a single global minimum.
Typically, the Advent of Code optimisation problems start small in part one so that any implementation is quick enough. But, in part two, a complication is introduced that makes the "obvious" solution inefficient. We start with a slightly better than brute-force optimisation, using a step size that halves with each iteration until a minimum is found.
First, we define a cost function.
def simplecost(crabpos: np.array, testpos: int) -> int:
"""Returns cost function for simple crab movements
:param crabpos: array of initial crab positions
:param testpos: position for cost calculation
"""
return sum(abs(crabpos - testpos))
Then we define the optimisation algorithm, taking the cost function as an argument. Splitting the functions in this way may simplify the second part, in case we only need to apply a different cost function.
def optpos(crabpos: np.array, func: Callable) -> Tuple[int, int]:
"""Returns best position and fuel cost
:param crabpos: array of initial crab positions
"""
# Initialise starting position (central), cost at
# that position, and the stepsize (half the distance
# from best position to crab position bounds)
best_pos = int(0.5 * (crabpos.max() + crabpos.min()))
mincost = func(crabpos, best_pos)
stepsize = max([crabpos.max() - best_pos, best_pos - crabpos.min()])
# At each iteration we establish a test position at
# the point stepsize away above and below the current
# best position.
# If the cost at either test position is lower than
# that at the best position, we move the best position
# to that position.
# If not, we reduce the stepsize by half.
# We will halt when the stepsize falls below 1 - at
# that point we have the minimum value
while stepsize:
# Establish test positions
testpos_up, testpos_dn = (min(crabpos.max(), best_pos + stepsize),
max(0, best_pos - stepsize))
# Cost at test positions
cost_up, cost_dn = (func(crabpos, testpos_up),
func(crabpos, testpos_dn))
# We move if the cost at either position is lower
if cost_up < mincost:
best_pos = testpos_up
mincost = cost_up
elif cost_dn < mincost:
best_pos = testpos_dn
mincost = cost_dn
else: # else we halve the stepsize
stepsize = int(0.5 * stepsize)
# Return the optimal position and the cost at that position
return best_pos, mincost
Solving the test problem.
crabpos = load_input(testpath)
optpos(crabpos, simplecost)
(2, 37)
And then the puzzle data.
crabpos = load_input(datapath)
optpos(crabpos, simplecost)
(342, 351901)
The crabs don't seem interested in your proposed solution. Perhaps you misunderstand crab engineering?
As it turns out, crab submarine engines don't burn fuel at a constant rate. Instead, each change of 1 step in horizontal position costs 1 more unit of fuel than the last: the first step costs 1, the second step costs 2, the third step costs 3, and so on.
As each crab moves, moving further becomes more expensive. This changes the best horizontal position to align them all on; in the example above, this becomes 5:
Move from 16 to 5: 66 fuel
Move from 1 to 5: 10 fuel
Move from 2 to 5: 6 fuel
Move from 0 to 5: 15 fuel
Move from 4 to 5: 1 fuel
Move from 2 to 5: 6 fuel
Move from 7 to 5: 3 fuel
Move from 1 to 5: 10 fuel
Move from 2 to 5: 6 fuel
Move from 14 to 5: 45 fuel
This costs a total of 168 fuel. This is the new cheapest possible outcome; the old alignment position (2) now costs 206 fuel instead.
Determine the horizontal position that the crabs can align to using the least fuel possible so they can make you an escape route! How much fuel must they spend to align to that position?
The difference in puzzle two is that the cost function involves more complex calculation, which would make a more naive optimisation inefficient.
Even though the optimisation function is probably fast enough (solutions to Advent of Code should usually finish in less than a second), we can make a useful improvement.
Each time we calculate the cost function, for each value in the array of crab positions $p_i$ we need to calculate the sum of values $1, 2, \ldots, p_i$. To speed things up, we can calculate this for the first time we see each $p_i$ and then cache it in a global dictionary CACHE
, keyed by $p_i$.
In addition, we can vectorise the calculation for application along a numpy
array.
We implement a new cost function, incorporating this.
# global cache of sums of 1 + 2 + ... + p_i,
# keyed by p_i
CACHE = {}
def movecost(dist: int) -> int:
"""Returns sum of 1+2+...+dist
:param dist: distance a crab has to travel
Uses the global cache to get a value for
dist, or calculates and updates the cache if
not present.
"""
if dist not in CACHE:
# sum of first n integers is n * (n+1) / 2
CACHE[dist] = int(0.5 * dist * (dist + 1))
return CACHE[dist]
# Vectorise the movecost() function
movecost_v = np.vectorize(movecost)
def diffcost(crabpos: np.array, testpos: int) -> int:
"""Returns cost of crab movement
:param crabpos: array of initial crab positions
:param testpos: position for cost calculation
Cost of movement is sum of 1+2+...+p_i for each p_i
in the crab positions.
"""
return sum(movecost_v(abs(crabpos - testpos)))
crabpos = load_input(testpath)
optpos(crabpos, diffcost)
(5, 168)
crabpos = load_input(datapath)
optpos(crabpos, diffcost)
(478, 101079875)