Skip to content

Instantly share code, notes, and snippets.

@mat3u
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mat3u/d864d371fe168db36ffe to your computer and use it in GitHub Desktop.
Save mat3u/d864d371fe168db36ffe to your computer and use it in GitHub Desktop.
//***
//*X*
//***
let vicinity (cx, cy) =
seq {
for x in -1..1 do
for y in -1..1 do
yield (cx + x, cy + y)
} |> Seq.filter (fun c -> c <> (cx, cy))
let contains' element world =
Seq.exists (fun c -> c = element) world
let contains element =
Seq.exists (fun c -> c = element)
// Seq.exists ((=) element)
let shouldBeAlive world (cell, ns) =
match ns with
| 3 -> true
| 2 when world |> contains cell -> true
| _ -> false
(* 111
x 212
x ->212
111
*)
let next world =
let world' = world |> Seq.toList
world'
|> Seq.collect vicinity
|> Seq.groupBy id
|> Seq.map (fun (c, v) -> (c, Seq.length v))
|> Seq.filter (shouldBeAlive world')
|> Seq.map fst
let sampleWorld = seq {
// Glider
yield (2, 0)
yield (2, 1)
yield (2, 2)
yield (1, 2)
yield (0, 1)
// Line
yield (20, 3)
yield (20, 4)
yield (20, 5)
}
let display' width height world =
System.Console.SetCursorPosition(0,0)
seq {
for x in 1..(height+1) do
for y in 1..width do
yield (x,y)
}
|> Seq.iteri (fun i c ->
match c with
| c when world |> contains c -> printf "X"
| _ -> printf "."
if (i+1) % width = 0 then printfn ""
)
|> ignore
let display = display' 50 25
System.Console.Clear()
let iterations = 100
seq { 1 .. iterations }
|> Seq.fold ( fun world n ->
display world
printfn "%A/%A" n iterations
System.Threading.Thread.Sleep(50)
next world
) sampleWorld
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment