aboutsummaryrefslogtreecommitdiff
path: root/aoc-2021-kotlin/src/Day11.kt
blob: db56d61af5866cea883da5e0d272b4f23bc72504 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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)
}