Snippet:
static void Part1(string data)
{
var result = ParseInput(data)
.Select(history => ProcessHistory(history, g => g.Length - 1, (a, b) => a + b))
.Sum();
Console.WriteLine(result);
}
static void Part2(string data)
{
var result = ParseInput(data)
.Select(history => ProcessHistory(history, g => 0, (a, b) => a - b))
.Sum();
Console.WriteLine(result);
}
static int ProcessHistory(
int[] history,
Func guessIndex,
Func collateGuess)
{
bool allZeros = true;
var diffs = new int[history.Length - 1];
for (int i = 0; i < diffs.Length; i++)
{
var diff = history[i + 1] - history[i];
diffs[i] = diff;
allZeros = allZeros && (diff == 0);
}
var guess = history[guessIndex(history)];
if (!allZeros)
{
guess = collateGuess(
guess,
ProcessHistory(diffs, guessIndex, collateGuess));
}
return guess;
}
Thanks for that state machine. I was a bit lost in part 2, but after reading this, it totally makes sense.