Skip to content

Instantly share code, notes, and snippets.

@BastiTee
Created August 8, 2018 06:56
Show Gist options
  • Save BastiTee/4d998aaf28818f53ba5032b900094904 to your computer and use it in GitHub Desktop.
Save BastiTee/4d998aaf28818f53ba5032b900094904 to your computer and use it in GitHub Desktop.
Game of Life functional in Kotlin
package com.acme.jvm
import java.util.stream.Stream
typealias Board = List<List<Boolean>>
fun step(board: Board) = board.mapIndexed { rowIdx, row ->
row.mapIndexed { colIdx, cellAlive ->
neighboursAlive(board, rowIdx, colIdx) in if (cellAlive) 2..3 else 3..3
}
}
fun neighboursAlive(board: Board, x: Int, y: Int) = neighbours(board, x, y).count { it }
fun neighbours(board: Board, x: Int, y: Int) = board.mapIndexed { rowIdx, row ->
row.filterIndexed { colIdx, _ ->
isNeighbour(rowIdx, colIdx, x, y)
}
}.flatten()
fun isNeighbour(rowIdx: Int, colIdx: Int, x: Int, y: Int) =
Math.abs(x - rowIdx) <= 1 && Math.abs(y - colIdx) <= 1 && (x != rowIdx || y != colIdx)
fun toMultiLineString(board: Board): String {
val sb = StringBuilder()
board.forEach{ row ->
row.forEach{ column -> sb.append(if (column) "Ö " else "† ") }
sb.append("\n")
}
return sb.toString()
}
fun main(args: Array<String>) {
val board = listOf(listOf(false, true, false), listOf(false, true, true), listOf(true, false, false))
Stream.iterate(board) { step(it) }
.limit(100)
.forEach { println(toMultiLineString(it)) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment