Created
April 28, 2012 12:54
-
-
Save otf/2518881 to your computer and use it in GitHub Desktop.
coderetreat
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
open System | |
type World<'a> = 'a [,] | |
let tryGet ar x y = | |
try Some <| Array2D.get ar x y | |
with e -> None | |
let countAlive = List.collect Option.toList >> List.filter ((=) true) >> List.length | |
let getNeighborCount board x y = | |
[ | |
for x2 in [-1 .. 1] do | |
for y2 in [-1 .. 1] do | |
yield (tryGet board (x + x2) (y + y2)) | |
] |> countAlive | |
let neighbors board = board |> Array2D.mapi (fun x y _ -> getNeighborCount board x y) | |
let zip ar = Array2D.mapi (fun x y cell -> (cell, Array2D.get ar x y)) | |
let fix a = (fun _ -> a) | |
let action = function | |
| (3, false) -> (fix true) | |
| (n, true) when n >= 4 || n <= 1 -> (fix false) | |
| _ -> id | |
let life world = | |
let fworld = zip world (neighbors world) |> Array2D.map action | |
zip world fworld |> Array2D.map (fun (f, c) -> f c) | |
let initWorld i = | |
let r = new Random () | |
Array2D.init i i (fun _ _ -> r.Next() % 2 = 1) | |
let pritty = Array2D.map (fun c -> if c then "●" else "○") | |
let update world = | |
printfn "====================================" | |
printf "%A" (world |> pritty) | |
Console.ReadLine () |> ignore | |
let lifeGame = Seq.unfold (fun prev -> Some (life prev, life prev)) | |
[<EntryPoint>] | |
let main args = | |
initWorld 10 |> lifeGame |> Seq.iter update | |
0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment