Navigation Menu

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/d9773c8aaca484ff2bc6 to your computer and use it in GitHub Desktop.
Save mat3u/d9773c8aaca484ff2bc6 to your computer and use it in GitHub Desktop.
type Cell = int * int
let exists_in element =
Seq.exists ((=) element)
let vicinity (x, y) =
seq {
for px in -1..1 do
for py in -1..1 do
yield (x+px, y+py)
} |> Seq.filter (fun c -> c <> (x,y))
let shouldSurvive (world: Cell seq) (cell : Cell, ns) =
match ns with
| 3 -> true
| 2 when exists_in cell world -> true
| _ -> false
let next world =
let world' = world |> Seq.toList
world'
|> Seq.collect vicinity
|> Seq.groupBy id
|> Seq.map (fun (k, v) -> (k, Seq.length v))
|> Seq.filter (shouldSurvive world')
|> Seq.map fst
let glider = seq {
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 world =
System.Console.SetCursorPosition(0,0)
seq {
for x in 1..26 do
for y in 1..25 do
yield (x,y)
}
|> Seq.mapi (fun i c ->
match c with
| c when exists_in c world -> printf "X"
| _ when (i % 25) = 0 -> printf "\n"
| _ -> printf "."
)
|> ignore
seq { 1 .. 100 }
|> Seq.fold ( fun world _ ->
display world
System.Threading.Thread.Sleep(200)
next world
) glider
|> ignore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment