Photo by Any Lane from Pexels

I’m participating in the Advent of Code 2021. Here’s my solutions for Day 7 - Whale Attack.

Problem 1

In the Puzzles for Day 7, we’re getting attacked by a whale who intends to swallow the submarine. To the rescue come a bunch of crabs in mini-subs. But they’re not in alignment to blast open a rescue tunnel. We have to get them to move into horizontal alignment using the least amount of total fuel possible. They all start in different positions, so the first puzzle focuses on the least amount of fuel required get them into a single horizontal alignment.

Solution

All my solutions are written in C#. You can find all my solutions in my Git repo.

For this one, I first figured out the average horizontal position for all the crab subs, then worked outward in both directions from the average, calculating the fuel cost to move all the crabs to that position. Probably not very efficient, but I eventually found it.

Console.WriteLine("Advent of Code 2021");
Console.WriteLine("Day 7 - Puzzle 1");

//Solution logic goes here

//Load input array
string[] lines = System.IO.File.ReadAllLines("input.txt");
var lineList = lines[0].Split(',');

var crabs = new int[lineList.Length];
for (int i = 0; i < lineList.Length; i++)
{
    crabs[i] = int.Parse(lineList[i]);
}

//find the range of values
int maxVal = crabs.Max();
int minVal = crabs.Min();
var avg = Convert.ToInt32(Math.Floor(crabs.Average()));

//now figure out fuel cost, starting at the average point
var costCompare = new Dictionary<int, int>();
for (int i = 0;i< 500; i++)
{
    var costSumPlus = 0;
    var costSumMinus = 0;

    var plus = avg + i;
    var minus = avg - i;

    foreach (var crab in crabs)
    {
        costSumPlus += Math.Abs(crab - plus);
        costSumMinus += Math.Abs(crab - minus);
    }

    costCompare[plus] = costSumPlus;
    costCompare[minus] = costSumMinus;
}

var minCost = costCompare.Min(x => x.Value);

Console.WriteLine($"The smallest fuel cost is: {minCost}");

//Stop and wait for enter before exiting
Console.ReadLine();

The answer is 331067

Puzzle 2

For the second puzzle, we find that for each move the crab subs make, it costs them 1 additional fuel. So first move costs one, second move costs 2, third move costs 3, etc. So to move 3 spaces costs 6 total fuel. Recalculate the least fuel cost using this logic.

Solution

For the second part I replaced the simple sum with a function that calculates the cost based on distance. So, for a distance of 6, the function should calculate it as: 6 + 5 + 4 + 3 + 2 + 1 = 21.

So, our crab loop becomes:

    foreach (var crab in crabs)
    {
        costSumPlus += FuelCalc(Math.Abs(crab - plus));
        costSumMinus += FuelCalc(Math.Abs(crab - minus));
    }

And our function is:

static int FuelCalc(int distance)
{
    var sum = 0;
    for (int x = 1; x <= distance; x++)
    {
        sum += x;
    }
    return sum;
} 

The answer is: 92881128