Created
October 15, 2012 23:02
-
-
Save irpap/3896215 to your computer and use it in GitHub Desktop.
One dimensional game of life
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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