Day 6 solution

Took me a while to come to the fast solution, but I got there.
This commit is contained in:
2021-12-05 23:55:15 -06:00
parent b8848ab334
commit 2cc95c6e8e
4 changed files with 86 additions and 0 deletions

View File

@ -30,6 +30,9 @@
<None Update="inputs\05.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="inputs\06.txt">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

1
inputs/06.txt Normal file
View File

@ -0,0 +1 @@
4,1,4,1,3,3,1,4,3,3,2,1,1,3,5,1,3,5,2,5,1,5,5,1,3,2,5,3,1,3,4,2,3,2,3,3,2,1,5,4,1,1,1,2,1,4,4,4,2,1,2,1,5,1,5,1,2,1,4,4,5,3,3,4,1,4,4,2,1,4,4,3,5,2,5,4,1,5,1,1,1,4,5,3,4,3,4,2,2,2,2,4,5,3,5,2,4,2,3,4,1,4,4,1,4,5,3,4,2,2,2,4,3,3,3,3,4,2,1,2,5,5,3,2,3,5,5,5,4,4,5,5,4,3,4,1,5,1,3,4,4,1,3,1,3,1,1,2,4,5,3,1,2,4,3,3,5,4,4,5,4,1,3,1,1,4,4,4,4,3,4,3,1,4,5,1,2,4,3,5,1,1,2,1,1,5,4,2,1,5,4,5,2,4,4,1,5,2,2,5,3,3,2,3,1,5,5,5,4,3,1,1,5,1,4,5,2,1,3,1,2,4,4,1,1,2,5,3,1,5,2,4,5,1,2,3,1,2,2,1,2,2,1,4,1,3,4,2,1,1,5,4,1,5,4,4,3,1,3,3,1,1,3,3,4,2,3,4,2,3,1,4,1,5,3,1,1,5,3,2,3,5,1,3,1,1,3,5,1,5,1,1,3,1,1,1,1,3,3,1

81
src/06.cs Normal file
View File

@ -0,0 +1,81 @@
using System.Diagnostics;
namespace aoc2021
{
internal class Day06
{
[DebuggerDisplay("{State}")]
struct Fish
{
public int State;
}
internal static void Go()
{
Logger.Log("Day 6");
Logger.Log("-----");
var input = File.ReadAllText("inputs/06.txt");
List<Fish> fish = new();
foreach (var state in input.Split(','))
{
fish.Add(new Fish() { State = Convert.ToInt32(state) });
}
Part1(fish);
Part2(fish);
Logger.Log("");
}
private static void Part1(IEnumerable<Fish> fish)
{
using var t = new Timer();
var list = fish.ToList();
// brute force method (my initial solution)
for (int day = 0; day < 80; day++)
{
for (int i = list.Count - 1; i >= 0; i--)
{
Fish f = list[i];
if (f.State == 0)
{
list.Add(new Fish() { State = 8 });
f.State = 7;
}
f.State--;
list[i] = f;
}
}
#pragma warning disable CA1829 // Use Length/Count property instead of Count() when available - Count is of type int, list might be longer than that
Logger.Log($"part1: #fish={list.LongCount()}");
#pragma warning restore CA1829 // Use Length/Count property instead of Count() when available
}
private static void Part2(IEnumerable<Fish> fish)
{
using var t = new Timer();
// fast method (when brute force threatened to blow RAM and take way too long)
Dictionary<int, long> fishAtState = new();
for (int i = 0; i <= 8; i++)
{
fishAtState[i] = fish.Count(x => x.State == i);
}
for (int day = 0; day < 256; day++)
{
var adders = fishAtState[0];
for (int i = 0; i < 8; i++)
{
fishAtState[i] = fishAtState[i + 1];
}
fishAtState[6] += adders;
fishAtState[8] = adders;
}
Logger.Log($"part2: #fish={fishAtState.Values.Sum()}");
}
}
}

View File

@ -1,3 +1,4 @@
aoc2021.Day02.Go();
aoc2021.Day03.Go();
aoc2021.Day05.Go();
aoc2021.Day06.Go();