Skip to content

Instantly share code, notes, and snippets.

@uskudnik
Created November 10, 2014 01:24
Show Gist options
  • Save uskudnik/3e04c2162a4926d5f373 to your computer and use it in GitHub Desktop.
Save uskudnik/3e04c2162a4926d5f373 to your computer and use it in GitHub Desktop.
Game of Life in Scala
object GameOfLife {
type Pos = (Int, Int)
type Alive = Boolean
type Weight = Int
type Grid = Map[Pos, Alive]
def findNeighbours(pos: Pos): List[Pos] = {
val T = List(-1 , 0, 1)
for {x <- T; y <- T if !(x == 0 && y == 0)} yield (x + pos._1, y + pos._2)
}
def isAliveChecker(grid: Grid, weights: Map[Pos, Weight]): Pos => Alive = pos => {
val wasAlive = grid(pos)
val w = weights(pos)
if (wasAlive && w >= 2 && w <= 3) true
else if (!wasAlive && w == 3) true
else false
}
def iter(g: Grid): Grid = {
val liveCells = g.withDefaultValue(false)
val nns = (for { xy <- liveCells.keys } yield (xy, findNeighbours(xy))).toMap
val allCells = nns.values.flatten.toSet
val weights = nns.values.flatten.groupBy(identity).map({ case (k, v) => (k, v.toList.length) }).toMap
lazy val isAlive = isAliveChecker(liveCells, weights)
(for { cell <- allCells if isAlive(cell) } yield (cell, true)).toMap
}
// blinker: {[1 0] [1 1] [1 2]}
// {[2 1] [1 1] [0 1]}
val blinker = Map(
(1, 0) -> true,
(1, 1) -> true,
(1, 2) -> true
)
assert(findNeighbours((1, 1)) == List((0,0), (0,1), (0,2), (1,0), (1,2), (2,0), (2,1), (2,2)))
assert(!(findNeighbours((1, 1)) contains((1, 1))))
assert(blinker == iter(iter(blinker)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment