--- Day 7: Crab Submarines ---

December 7

Listening to: Future Funk


This one's a silly problem - Crab Sumarines that can only move sidesways! I love it. If I was more artistically inclined, I'd want to draw them.

// Brute force it; check the fuel needed for all positions
int bestPos = 0, bestFuel = INT_MAX;

for (int i = 0; i < maxPos; i++) {
    int curFuel = 0;
    for (auto crab: crabs)
        curFuel += abs(crab - i);

    if (curFuel < bestFuel) {
        bestPos = i;
        bestFuel = curFuel;
    }
}

What would they look like? Would they have those little grabby arms, but only on the sides? Do they make a little shimmy wobble as they move around?


Okay, I know this number pattern, though I had to look up formulas for a bit. The fuel cost is a triangle pattern, with the cost being the nth number of that sequence. The naive way of calculating it is to calculate the whole of the sequence up to that point. But there's an easy formula for it that just goes:

0.5 * (n)(n+1)

Plug that in and...

for (auto crab: crabs) {
    int delta = abs(crab - i);
    curFuel += (delta * (delta+1)) / 2;
}

Do submarine crabs dance?


My solutions for today's puzzles