public
Created

One dimensional game of life

  • Download Gist
gistfile1.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
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)))
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.