r/backtickbot • u/backtickbot • Dec 15 '20
https://np.reddit.com/r/adventofcode/comments/kdf85p/2020_day_15_solutions/gfwpzy5/
C
I'd written this as an array with the number of turns for part one and searched backwards in the array each turn which worked great, but I should have known that the second part would be a huge number of turns and written it for that in the first place.
For part 2, I rewrote my solution with a Dictionary<int, int> where the key is the number that was spoken and the value is the turn where it was last spoken. This gives me a fairly quick lookup although it still took 3.4 seconds to solve.
public static int LastSpoken(int[] numbers, int stop)
{
Dictionary<int, int> spoken = new Dictionary<int, int>();
for (int i = 0; i < numbers.Length - 1; i++)
spoken[numbers[i]] = i + 1;
int lastSpoken = numbers[^1];
for (int i = numbers.Length; i < stop; i++)
{
int previous = WasSpoken(spoken, lastSpoken);
spoken[lastSpoken] = i;
lastSpoken = (previous != -1) ? i - previous : 0;
}
return lastSpoken;
}
// Returns the turn where the number was last spoken or -1 if it wasn't spoken
static int WasSpoken(Dictionary<int, int> spoken, int lastSpoken)
{
if (spoken.TryGetValue(lastSpoken, out int previous))
return previous;
return -1;
}
1
Upvotes