Created
June 17, 2015 18:45
-
-
Save janderit/286a958d33533d96930a to your computer and use it in GitHub Desktop.
Concise F# version of Conway's Game of Life
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
(* | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And yes, I know Console.Clear is not great performance.
That wasn't the point ;)