Skip to content

Instantly share code, notes, and snippets.

@andypetrella
Created August 7, 2013 06:10
Show Gist options
  • Save andypetrella/6171640 to your computer and use it in GitHub Desktop.
Save andypetrella/6171640 to your computer and use it in GitHub Desktop.
Game of Life (Conway) in scala
object conway {
def neighbours(p:(Int, Int)) =
for {
dx <- List(-1, 0, 1)
dy <- if (dx == 0) List(-1, 1) else List(-1, 0, 1)
} yield (dx+p._1, dy+p._2)
def step(cells:List[(Int, Int)]) =
cells
.flatMap(neighbours)
.groupBy(identity)
.mapValues(_.size)
.filter {
case (t, count) => (count == 3) || (count == 2 && cells.contains(t))
}
.toList
.map(_._1)
val board = List((1, 0), (1, 1), (1, 2))
def compute(n:Int) = Seq.iterate(board, n)(step)
def printGame(g:List[(Int,Int)], w:Int, h:Int) =
Seq.tabulate(w, h){ (i,j) =>
if (g.contains((i,j))) 'X' else 'O'
}.map(_.mkString).mkString("\n")
def print(i:Int, w:Int = 3, h:Int = 3) = compute(i).map(x => printGame(x,w,h)).foreach(x => {println("-"*w); println(x)})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment