Skip to content

Instantly share code, notes, and snippets.

@bartoszm
Created December 11, 2021 06:36
Show Gist options
  • Save bartoszm/c26b79b3fbba2f074196fc8bd0069d3a to your computer and use it in GitHub Desktop.
Save bartoszm/c26b79b3fbba2f074196fc8bd0069d3a to your computer and use it in GitHub Desktop.
package day11
import java.nio.file.Files
import java.nio.file.Path
class State(private val data: Array<IntArray>) {
val inner = data[0].size - 1
val outer = data.size - 1
val flashes by lazy { data.sumOf { row -> row.count { it == 0 } } }
fun evolve(): State {
val newState = data.copy()
val flashed = Array(outer + 1){ BooleanArray(inner+1) }
forAll { o, i -> newState[o][i] +=1 }
var modified: Boolean
do {
modified = false
forAll { o, i ->
if(newState[o][i] > 9 && !flashed[o][i]) {
neighbours(Pair(o,i))
.filter { !flashed[it.first][it.second] }
.forEach { newState[it.first][it.second] += 1 }
modified = true
flashed[o][i] = true
}
}
} while (modified)
forAll { o, i -> if(newState[o][i] > 9) newState[o][i] = 0 }
return State(newState)
}
private fun forAll(action: (Int,Int) -> Unit) {
(0..outer).forEach { a ->
(0..inner).forEach { b ->
action(a,b)
}
}
}
private fun neighbours(p: Pair<Int,Int>): Sequence<Pair<Int,Int>> {
return sequence {
((p.first-1)..(p.first+1)).forEach { o ->
((p.second-1)..(p.second+1)).forEach { i ->
if(o in 0..outer && i in 0..inner) {
val n = Pair(o, i)
if(n != p) {
yield(n)
}
}
}
}
}
}
}
fun Array<IntArray>.copy() = map { it.clone() }.toTypedArray()
object Day11_Part1 {
fun solve(state: State, steps: Int = 100): Int {
var s = state
val allStates = (1..steps).map {
val o = s.evolve()
s = s.evolve()
o
}
return allStates.map { it.flashes }.sum()
}
}
object Day11_Part2 {
fun solve(state: State): Int {
var s = state
val size = (state.outer + 1) * (state.inner +1)
var allFlashed: Boolean
var step = 0
do {
s = s.evolve()
allFlashed = s.flashes == size
step +=1
} while(!allFlashed)
return step
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment