Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@janderit
Created June 17, 2015 18:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save janderit/286a958d33533d96930a to your computer and use it in GitHub Desktop.
Save janderit/286a958d33533d96930a to your computer and use it in GitHub Desktop.
Concise F# version of Conway's Game of Life
(*
F# Game of life
Philip Jander
@ph_j
2015
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
https://creativecommons.org/licenses/by-nc-sa/3.0/
*)
module GameOfLife =
let private rng = new System.Random()
let random_cells (rx,ry) number = set [ for x in 1..number -> (rng.Next rx),(rng.Next ry) ]
let private printcell (x,y) =
if (x>=0 && y>=0 && y<=30 && x<=30) then
System.Console.SetCursorPosition(x,y)
System.Console.Write("#")
let print board =
System.Console.Clear()
board |> Set.iter printcell
let private envelope1 (x,y) = set [ for dx in -1..+1 do for dy in -1..+1 -> (x+dx,y+dy) ]
let private envelope = Set.map envelope1 >> Set.unionMany
let private active_neighbors cells cell = Set.intersect cells (envelope1 cell) |> Set.remove cell |> Set.count
let private cells_with_active_neighbors number active area = area |> Set.filter (fun cell -> (active_neighbors active cell) = number)
let step cells = Set.union (cells_with_active_neighbors 2 cells cells) (cells_with_active_neighbors 3 cells (envelope cells))
let rec main board : unit =
GameOfLife.print board
GameOfLife.step board |> main
main (GameOfLife.random_cells (20,20) 50)
@janderit
Copy link
Author

And yes, I know Console.Clear is not great performance.
That wasn't the point ;)

@SMoni
Copy link

SMoni commented Jun 20, 2015

Ruby's still faster ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment