AoC 2021 D7: The Treachery of Whales
| Problem statement | Source code | Tags: Mathematics
← Previous Back to AoC Index Next →
Part 1
We are only given 1000 crabs, so a brute-force solution is feasible. First, obviously we want the alignment position to be between the minimum and maximum initial positions of the crabs, because moving outside that range would be more distance for all crabs. So we can iterate through all positions from min to max, and for each position calculate the total fuel cost by summing up the distances from each crab to that position.
However, we can do better than that. Picture all crabs on the number line (sorted ascending), and some point between and . Assume that .
Then, when we move to the right by 1 unit, all crabs to the left of need to move 1 unit more, while all crabs to the right of need to move 1 unit less. Therefore, the total fuel cost changes by . This means that if , moving to the right decreases the fuel cost, and if , moving to the right increases the fuel cost. Therefore, the optimal position is at , which is the median of the initial positions. If there's an odd number of crabs, aligning at the middle element is optimal; if there's an even number of crabs, aligning anywhere between the two middle elements, inclusive, is optimal. Selecting the median can be done in time using the Quickselect algorithm, but since is small here, sorting the array and picking the middle element is sufficient.
Mathematically the objective is:
The derivative is:
Setting gives us the same conclusion as above: we want equal number of crabs on both sides of , plus a 0 if is odd.
Part 2
The brute-force solution is still feasible, but the median idea no longer works, because moving by 1 unit now changes the fuel cost by more complicated amounts. However, we can still use calculus to find the optimal position. The objective is now:
The derivative is:
If again , then . Setting gives:
Because , the term is between and . Therefore, the optimal position is in the range . This range only contains a single integer (the mean rounded to the nearest integer); this is the optimal position.