aboutsummaryrefslogtreecommitdiff
path: root/aoc-2021-kotlin/src/Day11.kt
diff options
context:
space:
mode:
authortchojnacki <tomaszchojnacki2001@gmail.com>2022-08-11 19:24:23 +0200
committertchojnacki <tomaszchojnacki2001@gmail.com>2022-08-11 19:24:23 +0200
commit0f1e145b80813ae2331b7dac5ace0c589654ad2a (patch)
tree25483b8239436dd5aed2fee8811caf0ba893c0bb /aoc-2021-kotlin/src/Day11.kt
parent85fb0396bed6a2129b12392941103924b1ab55be (diff)
downloadgleam_aoc2020-0f1e145b80813ae2331b7dac5ace0c589654ad2a.tar.gz
gleam_aoc2020-0f1e145b80813ae2331b7dac5ace0c589654ad2a.zip
Move subproject to avoid IntelliJ module name issues
Diffstat (limited to 'aoc-2021-kotlin/src/Day11.kt')
-rw-r--r--aoc-2021-kotlin/src/Day11.kt48
1 files changed, 48 insertions, 0 deletions
diff --git a/aoc-2021-kotlin/src/Day11.kt b/aoc-2021-kotlin/src/Day11.kt
new file mode 100644
index 0000000..db56d61
--- /dev/null
+++ b/aoc-2021-kotlin/src/Day11.kt
@@ -0,0 +1,48 @@
+object Day11 {
+ private fun flashSequence(input: Map<Pos2D, Int>) = sequence {
+ val map = input.toMutableMap()
+
+ while (true) {
+ val flashed = mutableSetOf<Pos2D>()
+ fun canFlash(entry: Map.Entry<Pos2D, Int>): 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<String>) = 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)
+}