aoc2021/aoc2021/Day07.cs

31 lines
902 B
C#
Raw Normal View History

2021-12-07 16:27:50 +00:00
namespace aoc2021;
/// <summary>
/// Day 7: <see href="https://adventofcode.com/2021/day/7"/>
/// </summary>
public sealed class Day07 : Day
{
2021-12-07 19:51:30 +00:00
private readonly List<long> _tape;
2021-12-07 16:27:50 +00:00
public Day07() : base(7, "The Treachery of Whales")
{
2021-12-07 19:51:30 +00:00
_tape = Input.First().Split(',').Select(long.Parse).OrderBy(i => i).ToList();
2021-12-07 16:27:50 +00:00
}
2021-12-07 19:51:30 +00:00
private static long ArithmeticSumTo(long n) => n * (n + 1) / 2L;
2021-12-07 16:27:50 +00:00
2021-12-12 20:09:41 +00:00
public override object Part1()
2021-12-07 16:27:50 +00:00
{
var i = _tape[_tape.Count / 2];
2021-12-12 20:09:41 +00:00
return _tape.Select(t => Math.Abs(t - i)).Sum();
2021-12-07 16:27:50 +00:00
}
2021-12-12 20:09:41 +00:00
public override object Part2()
2021-12-07 16:27:50 +00:00
{
var avg = (decimal)_tape.Sum() / _tape.Count;
2021-12-07 19:51:30 +00:00
var floor = _tape.Select(t => ArithmeticSumTo(Math.Abs(t - (long)Math.Floor(avg)))).Sum();
var ceil = _tape.Select(t => ArithmeticSumTo(Math.Abs(t - (long)Math.Ceiling(avg)))).Sum();
2021-12-12 20:09:41 +00:00
return Math.Min(floor, ceil);
2021-12-07 16:27:50 +00:00
}
}