Last active
February 1, 2018 17:43
-
-
Save jasonmc/c1aeabf77dc8c185a7198e7b02fe5006 to your computer and use it in GitHub Desktop.
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
(* | |
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