2021-12-06 09:27:57 -06:00
|
|
|
import std/[strutils, sequtils, tables, strformat]
|
|
|
|
import ./common
|
|
|
|
|
|
|
|
const DEFAULT_DAYS = 80
|
|
|
|
const CYCLE_DAYS = 7
|
|
|
|
const MATURING_DAYS = 2
|
|
|
|
|
2021-12-06 09:51:20 -06:00
|
|
|
proc lanternFish(input: string, days = DEFAULT_DAYS): int =
|
2021-12-06 09:46:49 -06:00
|
|
|
# a place to put newly-spawned fish that are not mature enough themselves to
|
|
|
|
# spawn within the cycle
|
2021-12-06 09:27:57 -06:00
|
|
|
var maturingFish: seq[(int, int)]
|
2021-12-06 09:46:49 -06:00
|
|
|
|
|
|
|
# here we will keep the counts of fish that spawn on a given day in the cycle
|
2021-12-06 09:27:57 -06:00
|
|
|
var fish = newSeq[int](CYCLE_DAYS)
|
2021-12-06 09:46:49 -06:00
|
|
|
|
|
|
|
# initialize our current fish counts based on the input
|
2021-12-06 09:51:20 -06:00
|
|
|
for i in input.split(',').mapIt(it.parseInt()): inc fish[i]
|
2021-12-06 09:46:49 -06:00
|
|
|
|
|
|
|
for day in 0..days:
|
|
|
|
let cycleDay = day mod CYCLE_DAYS
|
|
|
|
# since we're just about to decrement the days for all maturing fish, add
|
|
|
|
# 1 to offset and spawn our maturing fish
|
|
|
|
maturingFish.add((MATURING_DAYS+1, fish[cycleDay]))
|
|
|
|
|
|
|
|
# age maturing fish
|
2021-12-06 09:27:57 -06:00
|
|
|
for v in maturingFish.mitems(): dec v[0]
|
2021-12-06 09:46:49 -06:00
|
|
|
|
|
|
|
# if our oldest maturing fish have now matured move them to their place in
|
|
|
|
# the cycle
|
2021-12-06 09:27:57 -06:00
|
|
|
if maturingFish[0][0] == 0:
|
2021-12-06 09:46:49 -06:00
|
|
|
fish[cycleDay] += maturingFish[0][1]
|
2021-12-06 09:27:57 -06:00
|
|
|
maturingFish.delete(0)
|
2021-12-06 09:46:49 -06:00
|
|
|
|
|
|
|
# sum all fish counts plus the fish that were spawned two days ago
|
|
|
|
fish.foldl(a + b) + (if maturingFish[0][0] <= 1: maturingFish[0][1] else: 0)
|
2021-12-06 09:27:57 -06:00
|
|
|
|
2021-12-06 09:51:20 -06:00
|
|
|
let input = 6.loadInputText()
|
2021-12-06 09:27:57 -06:00
|
|
|
time("day 6 part 1"): echo input.lanternFish()
|
|
|
|
time("day 6 part 2"): echo input.lanternFish(256)
|
|
|
|
|
|
|
|
when not defined(release):
|
2021-12-06 09:51:20 -06:00
|
|
|
let testInput = "3,4,3,1,2"
|
2021-12-06 09:27:57 -06:00
|
|
|
doAssert testInput.lanternFish(18) == 26
|
|
|
|
doAssert testInput.lanternFish() == 5934
|
|
|
|
doAssert testInput.lanternFish(256) == 26984457539
|