48 lines
1.2 KiB
C#
48 lines
1.2 KiB
C#
// #define Day6
|
|
#if Day6
|
|
using System.Diagnostics;
|
|
var fish = File.ReadAllText("day6/input").Split(",")
|
|
.Select(long.Parse)
|
|
.GroupBy(x => x)
|
|
.ToDictionary(x => x.Key, x => x.LongCount());
|
|
|
|
fish[0] = 0;
|
|
fish[6] = 0;
|
|
fish[7] = 0;
|
|
fish[8] = 0;
|
|
|
|
Console.WriteLine(CalculateGrowth(80, Copy(fish)));
|
|
Console.WriteLine(CalculateGrowth(256, Copy(fish)));
|
|
|
|
long CalculateGrowth(int numberOfDays, Dictionary<long, long> fishState) {
|
|
while (numberOfDays > 0) {
|
|
long newFish = fishState[0];
|
|
for (int i = 0; i < 8; i++) {
|
|
fishState[i] = fishState[i + 1];
|
|
}
|
|
fishState[6] += newFish;
|
|
fishState[8] = newFish;
|
|
|
|
numberOfDays--;
|
|
}
|
|
return fishState.Values.Sum();
|
|
}
|
|
|
|
Dictionary<long, long> Copy(Dictionary<long, long> dict) {
|
|
return dict.ToDictionary(entry => entry.Key,
|
|
entry => entry.Value);
|
|
}
|
|
|
|
// O(n)
|
|
long[] fishAsArray = fish.OrderBy(x => x.Key).Select(x => x.Value).ToArray();
|
|
int i = 0;
|
|
int days = 256;
|
|
int spawn = 6;
|
|
while (days > 0) {
|
|
int newSpawn = (i + 7) % 9;
|
|
fishAsArray[newSpawn] += fishAsArray[i];
|
|
i = (i + 1) % 9;
|
|
days--;
|
|
}
|
|
Console.WriteLine(fishAsArray.Sum());
|
|
#endif |