53 lines
1.4 KiB
C#
53 lines
1.4 KiB
C#
using AdventOfCode.Core.Shared.IO;
|
|
|
|
namespace AdventOfCode.Solutions._2023
|
|
{
|
|
public class Day09 : IChallange
|
|
{
|
|
public int Year => 2023;
|
|
public int Day => 9;
|
|
|
|
private readonly IInputReader _inputReader;
|
|
|
|
public Day09(IInputReader inputReader)
|
|
{
|
|
_inputReader = inputReader;
|
|
_inputReader.SetInput(this);
|
|
}
|
|
|
|
public async Task<string> GetSolutionPart1()
|
|
{
|
|
long sum = 0;
|
|
await foreach (long[] list in _inputReader.ReadLineAsLongArray(" "))
|
|
{
|
|
sum += GetNextValue(list);
|
|
}
|
|
|
|
return sum.ToString();
|
|
}
|
|
|
|
public async Task<string> GetSolutionPart2()
|
|
{
|
|
long sum = 0;
|
|
await foreach (long[] list in _inputReader.ReadLineAsLongArray(" "))
|
|
{
|
|
sum += GetNextValue(list.Reverse().ToArray());
|
|
}
|
|
|
|
return sum.ToString();
|
|
}
|
|
|
|
private long GetNextValue(long[] list) => list[^1] + GetNextValueExtrapolated(list);
|
|
|
|
private long GetNextValueExtrapolated(long[] list)
|
|
{
|
|
long[] deltas = list.Skip(1).Select((v, i) => v - list[i]).ToArray();
|
|
if (deltas.All(d => d == 0))
|
|
{
|
|
return deltas[0];
|
|
}
|
|
|
|
return deltas[^1] + GetNextValueExtrapolated(deltas);
|
|
}
|
|
}
|
|
} |