From 34c2414304d59e76d52b96efe6bebebb4e75f086 Mon Sep 17 00:00:00 2001 From: tchojnacki Date: Thu, 11 Aug 2022 12:01:44 +0200 Subject: Move year 2021 into a subfolder --- 2021-kotlin/src/Day11.kt | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 2021-kotlin/src/Day11.kt (limited to '2021-kotlin/src/Day11.kt') diff --git a/2021-kotlin/src/Day11.kt b/2021-kotlin/src/Day11.kt new file mode 100644 index 0000000..db56d61 --- /dev/null +++ b/2021-kotlin/src/Day11.kt @@ -0,0 +1,48 @@ +object Day11 { + private fun flashSequence(input: Map) = sequence { + val map = input.toMutableMap() + + while (true) { + val flashed = mutableSetOf() + fun canFlash(entry: Map.Entry): Boolean = entry.value > 9 && !flashed.contains(entry.key) + + // 1) + map.forEach { (pos, energy) -> map[pos] = energy + 1 } + + // 2) + while (map.any(::canFlash)) { + map + .filter(::canFlash) + .forEach { (pos, _) -> + flashed.add(pos) + Pos2D.directions8.map { pos + it }.forEach { + if (map.containsKey(it)) { + map[it] = map[it]!! + 1 + } + } + } + } + + // 3) + flashed.forEach { map[it] = 0 } + + yield(flashed.size) + } + } + + fun bothParts(input: List) = flashSequence(parseToMap(input)).let { seq -> + seq.take(100).sum() to seq.indexOfFirst { it == 100 } + 1 + } +} + +fun main() { + val testInput = readInputAsLines("Day11_test") + val testOutput = Day11.bothParts(testInput) + check(testOutput.first == 1656) + check(testOutput.second == 195) + + val input = readInputAsLines("Day11") + val output = Day11.bothParts(input) + println(output.first) + println(output.second) +} -- cgit v1.2.3