import platform.posix.* import kotlin.math.* typealias Universe = List const val initial = """ .#................................................ ..#............................................... ###........................................#...... ...........................................#...... ...........................................#...... .................................................. .................................................. .................................................. .................................................. .................................................. .................................................. .................................................. .................................................. .................................................. .................................................. .................................................. .................................................. """ fun main2() { var universe = initial.trimIndent().lines() while (true) { universe.print() universe = universe.computeNextGeneration() usleep(200_000) } } fun Universe.print() = println(joinToString("\n")) fun Universe.computeNextGeneration() = mapIndexed { y, row -> val vicinityY = max(y - 1, 0)..min(y + 1, lastIndex) row.mapIndexed { x, cell -> val vicinityX = max(x - 1, 0)..min(x + 1, row.lastIndex) val neighbours = vicinityY.sumBy { neighbourY -> vicinityX.count { neighbourX -> this[neighbourY][neighbourX] == '#' } }.let { if (cell == '#') it - 1 else it } when (neighbours) { 3 -> '#' 2 -> cell else -> '.' } }.joinToString("") }