64 lines
1.7 KiB
Kotlin
64 lines
1.7 KiB
Kotlin
package be.vandewalleh.aoc.days
|
|
|
|
import be.vandewalleh.aoc.utils.BaseDay
|
|
import be.vandewalleh.aoc.utils.input.Day
|
|
|
|
@Day
|
|
class Day11 : BaseDay() {
|
|
|
|
private data class Point(val x: Int, val y: Int) {
|
|
fun adjacents() = listOf(
|
|
copy(y = y - 1),
|
|
copy(x = x + 1),
|
|
copy(y = y + 1),
|
|
copy(x = x - 1),
|
|
copy(y = y - 1, x = x - 1),
|
|
copy(x = x + 1, y = y + 1),
|
|
copy(y = y + 1, x = x - 1),
|
|
copy(x = x + 1, y = y - 1),
|
|
)
|
|
}
|
|
|
|
private val map by lazy {
|
|
input.lines.value.flatMapIndexed { y, line ->
|
|
line.mapIndexed { x, value -> Point(x, y) to value.digitToInt() }
|
|
}.toMap()
|
|
}
|
|
|
|
override fun part1(): Int {
|
|
val map = map.toMap(HashMap())
|
|
var count = 0
|
|
repeat(100) { count += step(map) }
|
|
return count
|
|
}
|
|
|
|
private fun step(map: HashMap<Point, Int>): Int {
|
|
map.keys.forEach { map[it] = map[it]!! + 1 }
|
|
val flashed = hashSetOf<Point>()
|
|
while (true) {
|
|
val new = map.entries.asSequence()
|
|
.filter { it.value > 9 }
|
|
.filter { it.key !in flashed }
|
|
.onEach { flashed += it.key }
|
|
.flatMap { it.key.adjacents() }
|
|
.filter { it in map }
|
|
.toList()
|
|
|
|
if (new.isEmpty()) break
|
|
new.forEach { map[it] = map[it]!! + 1 }
|
|
}
|
|
|
|
map.entries.filter { it.value > 9 }
|
|
.map { it.key }
|
|
.forEach { map[it] = 0 }
|
|
|
|
return flashed.size
|
|
}
|
|
|
|
override fun part2(): Int {
|
|
val map = map.toMap(HashMap())
|
|
repeat(10000) { if (step(map) == map.size) return it + 1 }
|
|
return -1
|
|
}
|
|
}
|