Skip to content

Instantly share code, notes, and snippets.

@sbycrosz
Last active August 29, 2015 14:25
Show Gist options
  • Save sbycrosz/7e2d7aba2caccdf7ae3f to your computer and use it in GitHub Desktop.
Save sbycrosz/7e2d7aba2caccdf7ae3f to your computer and use it in GitHub Desktop.
Game of Life
package kata
object GameOfLife {
type World = List[List[Int]]
type Position = (Int, Int)
val DEAD = 0
val ALIVE = 1
def run(world: World): World = {
val (width, length) = size(world)
for (x <- (0 until width).toList)
yield for(y <- (0 until length).toList)
yield nextState(world, (x, y))
}
def nextState(world: World, p: Position) = {
val neighborCount = getAliveNeighborsCount(world, p)
world(p._1)(p._2) match {
case ALIVE if neighborCount < 2 || neighborCount > 3 =>
DEAD
case DEAD if neighborCount == 3 =>
ALIVE
case currentState: Int =>
currentState
}
}
def getAliveNeighborsCount(world: World, p: Position) = {
(for {xOffset <- -1 to 1
yOffset <- -1 to 1
neighborPosition = (p._1 + xOffset, p._2 + yOffset)
if withinWorld(world, neighborPosition) && (xOffset, yOffset) != (0, 0)}
yield world(neighborPosition._1)(neighborPosition._2)).sum
}
def size(world: World): (Int, Int) =
(world.size, world.head.size)
def withinWorld(world: World, p: Position) = {
val (width, length) = size(world)
p._1 < width && p._1 >= 0 && p._2 < length && p._2 >= 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment