Skip to content

Instantly share code, notes, and snippets.

@mavnn
Created November 21, 2014 12:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mavnn/4c390e372d649721ed9d to your computer and use it in GitHub Desktop.
Save mavnn/4c390e372d649721ed9d to your computer and use it in GitHub Desktop.
Conway's Game of Life (1 hour, 74 lines...)
open System
let (|Alive|Dead|) i =
match i with
| 0 -> Dead
| 1 -> Alive
| _ -> failwith "What?"
let rand = Random()
let testBoard =
Array2D.init 10 10 (fun x y -> rand.Next(0, 2))
// assume boundary is dead...
let ``surroundings old`` grid x y =
let xMin = max 0 (x - 1)
let xMax = min (x + 1) (Array2D.length1 grid - 1)
let yMin = max 0 (y - 1)
let yMax = min (y + 1) (Array2D.length2 grid - 1)
grid.[xMin..xMax,yMin..yMax]
let surroundings grid x y =
Array2D.init 3 3
(fun x' y' ->
let realX =
match x' with
| _ when x + (x' - 1) >= 0 && x + (x' - 1) < (Array2D.length1 grid) ->
x + (x' - 1)
| _ when x + (x' - 1) = -1 ->
(Array2D.length1 grid) - 1
| _ -> 0
let realY =
match y' with
| _ when y + (y' - 1) >= 0 && y + (y' - 1) < (Array2D.length2 grid) ->
y + (y' - 1)
| _ when y + (y' - 1) = -1 ->
(Array2D.length2 grid) - 1
| _ -> 0
grid.[realX,realY])
let countAlive s =
s |> Seq.cast<int> |> Seq.sum
let isAlive grid x y =
Array2D.get grid x y
let lives count alive =
let touching = count - alive
match alive with
| Alive ->
match touching with
| i when i < 2 -> 0
| i when i > 3 -> 0
| _ -> 1
| Dead ->
match touching with
| i when i = 3 -> 1
| _ -> 0
let gen previous =
Array2D.init (Array2D.length1 previous) (Array2D.length2 previous)
(fun x y ->
let count =
surroundings previous x y
|> countAlive
let alive =
isAlive previous x y
lives count alive)
let writeBoard grid =
Array2D.iteri (fun x y (i : int) ->
Console.SetCursorPosition(x, y)
Console.Write(i))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment