-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
47 lines (34 loc) · 1.16 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using AdventOfCode.Common;
var positions = Resources.GetInputFileLines().First().SplitToNumbers();
static (int[], int, int) CreateHistogram(IEnumerable<int> positions)
{
var min = positions.Min();
var max = positions.Max();
var histogram = new int[max - min + 1];
foreach (var i in positions)
{
histogram[i - min]++;
}
return (histogram, min, max);
}
static long GetFuelNeeded(int[] histogram, int position, bool constantConsumption)
{
long fuel = 0;
for (int i = 0; i < histogram.Length; i++)
{
long distance = Math.Abs(i - position);
if (!constantConsumption)
{
distance = distance * (distance + 1) / 2;
}
fuel += distance * histogram[i];
}
return fuel;
}
static long GetMinFuelNeeded(IEnumerable<int> positions, bool constantConsumption)
{
var (histogram, min, max) = CreateHistogram(positions);
return Enumerable.Range(min, max - min).Select(i => GetFuelNeeded(histogram, i - min, constantConsumption)).Min();
}
Console.WriteLine($"Part 1: {GetMinFuelNeeded(positions, true)}");
Console.WriteLine($"Part 2: {GetMinFuelNeeded(positions, false)}");