From 6fdc27771fd86ce071811251913328b9a9d83e29 Mon Sep 17 00:00:00 2001 From: Daniel Flanagan Date: Mon, 13 Dec 2021 11:04:24 -0600 Subject: [PATCH] Day 11 done --- 2021/nim/common.nim | 8 ++++---- 2021/nim/day11.nim | 42 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/2021/nim/common.nim b/2021/nim/common.nim index 750363b..ee61017 100644 --- a/2021/nim/common.nim +++ b/2021/nim/common.nim @@ -44,15 +44,15 @@ proc doDay*[T]( expectedPart1: int, expectedPart2: int): void = time(&"day {day} part 1"): echo day.inputLoader().part1() - # time(&"day {day} part 2"): echo day.inputLoader().part2() + time(&"day {day} part 2"): echo day.inputLoader().part2() when not defined(release): var p1 = testInput.part1() echo p1 doAssert p1 == expectedPart1 - # var p2 = testInput.part2() - # echo p2 - # doAssert p2 == expectedPart2 + var p2 = testInput.part2() + echo p2 + doAssert p2 == expectedPart2 proc reduce*[T, X](s: openArray[T], op: (X, T) -> X, init: X): X = result = init diff --git a/2021/nim/day11.nim b/2021/nim/day11.nim index 2122be3..05f99be 100644 --- a/2021/nim/day11.nim +++ b/2021/nim/day11.nim @@ -39,7 +39,45 @@ proc octopi(input: seq[seq[int]]): int = for f in allFlashes.items(): o[f[0]][f[1]] = 0 -doDay 11, n => n.loadInput().toGrid(), octopi, octopi, +proc octopiUntilAll(input: seq[seq[int]]): int = + var o = input + let h = o.len + let w = o[0].len + # echo &"w{w} h{h}" + for n in 1..1000000: + # for nums in o: + # echo nums.mapIt($it).join() + # echo n + var allFlashes = toHashSet[(int, int)] [] + var flashes = toHashSet[(int, int)] [] + for y in 0.. 9: + # echo &"Flash {y}, {x}" + inc result + flashes.incl (y, x) + allFlashes.incl (y, x) + while flashes.len > 0: + let (y, x) = flashes.pop + # echo &"Handling flash {y}, {x}" + for p in product @[@[y-1, y, y+1], @[x-1, x, x+1]]: + let (fy, fx) = (p[0], p[1]) + if fx < 0 or fy < 0 or fx >= w or fy >= h or (fx == x and fy == y): continue + # inc and check flashes + inc o[fy][fx] + if o[fy][fx] > 9 and not allFlashes.contains (fy, fx): + # echo &"Subflash {fy}, {fx}" + inc result + flashes.incl (fy, fx) + allFlashes.incl (fy, fx) + if allFlashes.len() == (w * h): + return n + for f in allFlashes.items(): + o[f[0]][f[1]] = 0 + +doDay 11, n => n.loadInput().toGrid(), octopi, octopiUntilAll, @[ "5483143223", "2745854711", @@ -51,4 +89,4 @@ doDay 11, n => n.loadInput().toGrid(), octopi, octopi, "6882881134", "4846848554", "5283751526", - ].toGrid(), 1656, 288957 + ].toGrid(), 1656, 195