Last active
August 29, 2015 14:09
-
-
Save ikusalic/822b29a71ced07603541 to your computer and use it in GitHub Desktop.
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
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