Skip to content

Instantly share code, notes, and snippets.

@robertberry-zz
Created December 19, 2014 16:01
Show Gist options
  • Save robertberry-zz/37089621a981432662d3 to your computer and use it in GitHub Desktop.
Save robertberry-zz/37089621a981432662d3 to your computer and use it in GitHub Desktop.
gol.scala
case class Position(x: Int, y: Int)
object Grid {
val Width = 10
val Height = 10
val grid = Map(
Position(0, 0) -> true
)
def go(grid: Set[Position]): Set[Position] = {
//(0 to Width)
val positions = (for {
x <- 0 until Width
y <- 0 until Height
} yield Position(x, y)).toList
positions.foldLeft(Set.empty[Position]) {
(newGrid, position) =>
if (grid.contains(position)) {
val px = position.x
val py = position.y
val neighbours = Set(Position(px + 1, py + 1),
Position(px, py + 1),
Position(px - 1, py +1),
Position(px - 1, py -1),
Position(px, py-1),
Position(px+1,py-1),
Position(px+1,py)
)
val liveNeighbours = neighbours.intersect(grid)
if (liveNeighbours.size < 2 || liveNeighbours.size > 3) newGrid
else newGrid + position
} else newGrid
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment