Skip to content

Instantly share code, notes, and snippets.

@irpap
Created October 15, 2012 23:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save irpap/3896215 to your computer and use it in GitHub Desktop.
Save irpap/3896215 to your computer and use it in GitHub Desktop.
One dimensional game of life
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FunSuite
@RunWith(classOf[JUnitRunner])
class GameOfLifeTest extends FunSuite {
type Rules = ((Int, Int, Int)) => Int
case class TheRules(rules: List[Int]) extends Rules {
def apply(tuple: (Int, Int, Int)) = {
val (a, b, c) = tuple
val index = c + b * 2 + a * 4
rules(index)
}
}
case class GameOfLife(state: List[Int]) {
def step(implicit rules: Rules) = {
val tuplesList = (state.reverse.head :: state ::: state.head :: Nil).sliding(3)
GameOfLife((for (list <- tuplesList) yield
list match {
case a :: b :: c :: Nil => rules((a, b, c))
}).toList)
}
}
test("(0,1,0) becomes (0,0,1) after one step") {
implicit val rules = TheRules(List(0, 0, 0, 1, 1, 0, 0, 0))
val game = GameOfLife(List(0, 1, 0))
val next = game.step
assert(next == GameOfLife(List(0, 0, 1)))
}
test("(0,1,1) becomes (0,1,0) after one step") {
implicit val rules = TheRules(List(0, 0, 0, 1, 1, 0, 0, 0))
val game = GameOfLife(List(0, 1, 1))
val next = game.step
assert(next == GameOfLife(List(0, 1, 0)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment