Guest User

Untitled

a guest
Sep 16th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.81 KB | None | 0 0
  1. open System
  2.  
  3. type State =
  4.     | Dead = 0
  5.     | Alive = 1
  6.  
  7. let size = 10
  8.  
  9. let mutable grid = Array2D.create size size State.Dead
  10.  
  11. let spawn (lst : (int * int) list) = for (x, y) in lst do grid.[y, x] <- State.Alive
  12.  
  13. let printGrid () =
  14.     let row = (Array2D.length1 grid) - 1
  15.     let col = (Array2D.length2 grid) - 1
  16.     for y in [0..row] do
  17.         for x in [0..col] do
  18.             Console.Write((int) grid.[y, x])
  19.         Console.WriteLine("\n")
  20.  
  21. let isValidCell (x, y) = (x > 0 && y > 0 && x < size && y < size)
  22.  
  23. let liveNeighbors (x, y) =
  24.     [for i in [-1 .. 1] do
  25.         for j in [-1 .. 1] do yield (x + i, y + j)]
  26.     |> List.filter (fun (i, j) -> (i > 0 && j > 0 && i < size && j < size))
  27.     |> List.filter (fun p -> p <> (x, y))
  28.     |> List.map (fun (x, y) -> grid.[y, x])
  29.     |> List.filter (fun x -> x = State.Alive)
  30.  
  31. let countElems l =
  32.     let rec loop l acc =
  33.         match l with
  34.             |h::t -> loop t (acc+1)
  35.             |[] -> acc
  36.     loop l 0
  37.  
  38. let tick () =
  39.     let tempGrid = Array2D.create size size State.Dead
  40.     let row = (Array2D.length1 grid) - 1
  41.     let col = (Array2D.length2 grid) - 1
  42.     for y in [0..row] do
  43.         for x in [0..col] do
  44.             let count = countElems(liveNeighbors (y, x))
  45.             match tempGrid.[y, x] with
  46.                 | State.Dead -> if count = 3 then tempGrid.[y, x] <- State.Alive
  47.                 | State.Alive -> if count <> 2 && count <> 3 then tempGrid.[y, x] <- State.Dead
  48.                 | _ -> printfn "LOLDONGS"
  49.     grid <- tempGrid
  50.  
  51. let play max =
  52.     let rec loop max acc =
  53.         printGrid()
  54.         tick()
  55.         match acc with
  56.             | max -> printfn "LOLDONE"
  57.             | _ -> loop max (acc + 1)
  58.     loop max 0
  59.  
  60. spawn [(2, 1); (2, 2); (2, 3); (1, 3); (0, 2)]
  61. play(10)
  62. Console.ReadLine() |> ignore
Add Comment
Please, Sign In to add comment