Created
September 6, 2011 21:41
-
-
Save jedws/1199058 to your computer and use it in GitHub Desktop.
Another conway
This file contains 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
package object conway3 { | |
type Gen = (Int, Int) => Boolean | |
type Calculator = Gen => Gen | |
type Size = Int | |
val nextCell: Boolean => Int => Boolean = | |
old => mates => if (mates > 3) false else if (mates == 3) true else (old && mates == 2) | |
val wrapper: Size => Int => Int = | |
size => i => if (i < 0) size + i else if (i >= size) i % size else i | |
/** Function for working out the next generation's value for a board */ | |
val next: Size => Calculator = size => { | |
val wrap = wrapper(size) | |
old => (a, b) => { | |
val (x, y) = (wrap(a), wrap(b)) | |
val (l, r, u, d) = (wrap(x - 1), wrap(x + 1), wrap(y - 1), wrap(y + 1)) | |
val mates = List((l, u), (l, y), (l, d), (x, u), (x, d), (r, u), (r, y), (r, d)) | |
nextCell { old(x, y) } { mates filter { old.tupled } size } | |
} | |
} | |
implicit def asCoord(as: Array[Array[Boolean]]): Gen = (x, y) => as(x)(y) | |
val memo: Size => Calculator = s => c => Array.tabulate(s, s) { c } | |
val stream: Size => Gen => Stream[Gen] = size => init => { | |
val next1 = next(size) andThen memo(size) | |
def loop(old: Gen): Stream[Gen] = old #:: loop(next1(old)) | |
loop(init) | |
} | |
val render: Size => Gen => String = | |
size => c => { | |
val sb = new StringBuilder((size * size) + size, "") | |
for (x <- 0 until size) { | |
for (y <- 0 until size) | |
sb.append(if (c(x, y)) "•" else " ") | |
sb.append("\n") | |
} | |
sb toString | |
} | |
def debug(x:Int, y:Int) { println("x: " + x + " y: " + y); ((x + y) & 1) == 0 } | |
} | |
package conway3 { | |
class Board(size: Size) extends Gen { | |
val array = Array.ofDim[Boolean](size, size) | |
def apply(x: Int, y: Int) = array(x)(y) | |
def set(x: Int, y: Int): this.type = { array(x)(y) = true ; this } | |
} | |
object Board { | |
def random(s: Size) = asCoord(Array.tabulate(s, s) { (_, _) => util.Random.nextBoolean }) | |
def glider(s: Size) = { | |
new Board(s).set(3, 3).set(3, 4).set(3, 5).set(2, 5).set(1, 4) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment