Skip to content

Instantly share code, notes, and snippets.

@ikusalic
Last active August 29, 2015 14:09
Show Gist options
  • Save ikusalic/822b29a71ced07603541 to your computer and use it in GitHub Desktop.
Save ikusalic/822b29a71ced07603541 to your computer and use it in GitHub Desktop.
object Cell {
def willLive(isAlive: Boolean, neighbourCount: Int): Boolean =
if (isAlive) neighbourCount == 2 || neighbourCount == 3
else neighbourCount == 3
}
case class GridPosition(x: Int, y: Int)
object Game {
type CellCollection = Set[GridPosition]
def evolve(current: CellCollection): CellCollection = {
def neighbourhood(pos: GridPosition): CellCollection =
(for (dx <- Seq(-1, 0, 1); dy <- Seq(-1, 0, 1)) yield GridPosition(pos.x + dx, pos.y + dy)).toSet
def neighboursCount(pos: GridPosition) =
(neighbourhood(pos) - pos)
.foldLeft(0) { case (sum, pos) => if (current.contains(pos)) sum + 1 else sum }
current
.flatMap(neighbourhood)
.filter { pos => Cell.willLive(isAlive = current.contains(pos), neighboursCount(pos)) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment