Last active
March 3, 2017 12:00
-
-
Save yoavst/1291aacd6dccc2b1e23f3172fd312965 to your computer and use it in GitHub Desktop.
Game of Life
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.yoavst.testing | |
fun main(args: Array<String>) { | |
/* | |
* Read cells. | |
* Format: y,x | |
* Where y,x are zero based. | |
* Stops when receive input "stop". | |
*/ | |
val input = generateSequence { readLine()?.takeIf { it != "stop" }?.split(',')?.let { (y, x) -> x.toInt() to y.toInt() } } | |
// Generate matrix of dim*dim, given the input. | |
var data = List(dim * dim) { Pair(it % dim, it / dim) in input } | |
// storage for (max alive, turn for max). | |
var results = data.size to 0 | |
// run for 50 generations. | |
for (gen in 1..50) { | |
/* | |
* Generate next generation. | |
* For each cell: | |
* - Count how many neighbors it has. if between 3-5, stay alive, otherwise die. | |
*/ | |
data = data.mapIndexed { i, _ -> moves.count { (dx, dy) -> data[fixed(i.x() + dx) + fixed(i.y() + dy) * dim] } in 3..5 } | |
data.size.let { | |
if (it > results.first) results = it to gen | |
println("gen $gen, alive: $it") | |
} | |
} | |
println("best gen is ${results.second}") | |
} | |
const val dim = 10 | |
// neighborhood | |
val moves = arrayOf(1 to 1, 1 to 0, 1 to -1, -1 to 0, -1 to 1, -1 to -1, 0 to 1, 0 to -1) | |
// fix bounds | |
inline fun fixed(num: Int) = if (num >= dim) 0 else if (num < 0) dim - 1 else num | |
inline fun Int.x() = this % dim | |
inline fun Int.y() = this / dim |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment