Random.self_init () type cell = Dead | Alive let cell_to_string = function | Alive -> "#" | Dead -> "_" let cell_to_int = function | Alive -> 1 | Dead -> 0 let random_cell = fun _ -> if Random.bool () then Dead else Alive ;; let random_row = fun _ -> Array.init 10 random_cell ;; let random_grid () = Array.init 10 random_row ;; let empty_grid () = Array.init 10 (fun _ -> Array.make 10 Dead) ;; let grid = ref (random_grid ()) ;; let show_row row = for x = 0 to 9 do cell_to_string row.(x) |> print_string done; print_newline () ;; let show_grid () = for y = 0 to 9 do show_row !grid.(y) done let read_cell x y = !grid.(y mod 10).(x mod 10) ;; let neighbors x y = (read_cell (x + 9) (y + 9) |> cell_to_int) + (read_cell x (y + 9) |> cell_to_int) + (read_cell (x + 1) (y + 9) |> cell_to_int) + (read_cell (x + 9) y |> cell_to_int) + (read_cell (x + 1) y |> cell_to_int) + (read_cell (x + 9) (y + 1) |> cell_to_int) + (read_cell x (y + 1) |> cell_to_int) + (read_cell (x + 1) (y + 1) |> cell_to_int) let next_state x y = match read_cell x y, neighbors x y with | (Dead, 3) -> Alive | (Alive, 2) | (Alive, 3) -> Alive | _ -> Dead let update_grid () = let next_grid = empty_grid () in for y = 0 to 9 do for x = 0 to 9 do next_grid.(y).(x) <- next_state x y done done; grid := next_grid ;; while true do show_grid () ; print_newline () ; update_grid () ; let _ = read_line () in () ; done