Skip to content

Instantly share code, notes, and snippets.

@jasonmc
Last active February 1, 2018 17:43
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 jasonmc/c1aeabf77dc8c185a7198e7b02fe5006 to your computer and use it in GitHub Desktop.
Save jasonmc/c1aeabf77dc8c185a7198e7b02fe5006 to your computer and use it in GitHub Desktop.
(*
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Author: Jason McCandless
*)
open System
let cartesian xs ys=
xs |> List.collect (fun x -> ys |> List.map (fun y -> x, y))
let liveNeighborCount grid x y =
cartesian [max (x-1) 0 .. min (x+1) (Array2D.length1 grid - 1)]
[max (y-1) 0 .. min (y+1) (Array2D.length2 grid - 1)]
|> Seq.filter(fun (i,j) -> (x <> i || y <> j) && grid.[i, j])
|> Seq.length
let computeCellAlive currentState count =
count = 3 || (count = 2 && currentState)
let computeNextGeneration grid =
grid |> Array2D.mapi (fun x y e -> computeCellAlive e (liveNeighborCount grid x y))
let run grid =
Seq.initInfinite ignore |> Seq.scan (fun g _ -> computeNextGeneration g) grid
let printGrid grid =
for row in 0 .. (Array2D.length1 grid) - 1 do
for col in 0 .. (Array2D.length2 grid) - 1 do
if grid.[row, col] then Console.Write("█")
else Console.Write(" ")
Console.WriteLine()
let main args =
let rnd = Random()
let start = Array2D.init<bool> 40 80 (fun _ _ -> (rnd.NextDouble() >= 0.5))
run start //|> Seq.take 200
|> Seq.iter (fun x -> (Threading.Thread.Sleep 200
Console.Clear(); printGrid x))
main [||]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment