Advent of Code - Day 6, 2021
Advent of Code is back and this particular problem was fairly interesting:
The first part of the puzzle can certainly be solved with simulation. Not the second one, though. Since the second one is in the trillions, simulation will run forever. A better approach is to do the following:
1/ Use a bucket approach, where you count the instance of all numbers from 0..8
2/ Each day, save off the number of elements in bucket[0]
3/ Every bucket will receive the value from the subsequent one (j <- j+1)
4/ At the end, use the value from #2 to update bucket[6] and bucket[8]
5/ Count them all and return
The time complexity is O(9 * NDays). Since NDays is 256, this becomes ridiculously fast. Code is below, but not the answer to avoid spoilers. Cheers, ACC.
using System;
using System.Numerics;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace AdventOfCode2021
{
class Day6
{
public BigInteger Puzzle1(string inputFile)
{
FileInfo fi = new FileInfo(inputFile);
StreamReader sr = fi.OpenText();
string line = sr.ReadLine().Trim();
sr.Close();
string[] parts = line.Split(',');
List fish = new List();
foreach (string part in parts) fish.Add(Int32.Parse(part));
int NDAYS = 80;
return LanternFishGrowth(fish, NDAYS);
}
public BigInteger Puzzle2(string inputFile)
{
FileInfo fi = new FileInfo(inputFile);
StreamReader sr = fi.OpenText();
string line = sr.ReadLine().Trim();
sr.Close();
string[] parts = line.Split(',');
List fish = new List();
foreach (string part in parts) fish.Add(Int32.Parse(part));
int NDAYS = 256;
return LanternFishGrowth(fish, NDAYS);
}
private BigInteger LanternFishGrowth(List fish, int nDays)
{
BigInteger[] timer = new BigInteger[9];
foreach (int n in fish) timer[n]++;
for (int i = 0; i < nDays; i++)
{
BigInteger timer0 = timer[0];
for (int j = 0; j < timer.Length - 1; j++)
timer[j] = timer[j + 1];
timer[6] += timer0;
timer[8] = timer0;
}
BigInteger retVal = 0;
foreach (BigInteger t in timer) retVal += t;
return retVal;
}
}
}
Comments
Post a Comment