using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace _2021___Day_07 { class Program { static void Main(string[] args) { List<int> input = File.ReadAllText("../../../../Input.in").Split(',').Select(int.Parse).ToList(); Console.WriteLine($"The crabs need {OptimalFuel(input, num => num)} fuel minimum"); Console.WriteLine($"But they actually require {OptimalFuel(input, num => num * (1 + num) / 2)} fuel minimum"); } static public int OptimalFuel(List<int> input, Func<int, int> fuelFunk) { int maxDistance = input.Max(); var crabs = input .GroupBy(x => x) .Select(x => (x.Key, x.Count())); var sumDist = new int[maxDistance + 1]; foreach (var c in crabs) { for (int j = 0; j <= maxDistance; j++) sumDist[j] += fuelFunk(Math.Abs(j - c.Item1)) * c.Item2; } return sumDist.Min(); } } }