01020304050607080910111213141516171819202122232425

Advent of Code

2021/7

The Treachery of Whales

in C#

by encse

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!

Read the full puzzle.

using System;
using System.Linq;

namespace AdventOfCode.Y2021.Day07;

[ProblemName("The Treachery of Whales")]
class Solution : Solver {

    public object PartOne(string input) => 
        FuelMin(input, fuelConsumption: distance => distance);

    public object PartTwo(string input) => 
        FuelMin(input, fuelConsumption: distance => (1 + distance) * distance / 2);
        
    int FuelMin(string input, Func<int, int> fuelConsumption) {
        var positions = input.Split(",").Select(int.Parse).ToArray();

        var totalFuelToReachTarget = (int target) => 
            positions.Select(position => fuelConsumption(Math.Abs(target - position))).Sum();

        // Minimize the total fuel consumption checking each possible target position.
        // We have just about 1000 of these, so an O(n^2) algorithm will suffice.
        var minPosition = positions.Min();
        var maxPosition = positions.Max();
        return Enumerable.Range(minPosition, maxPosition - minPosition + 1).Select(totalFuelToReachTarget).Min();
    }
}

Please ☆ my repo if you like it!

© 2025 Advent of Code is a registered trademark in the US Images provided by Bing image creator