我正在尝试制作一个函数,让我获得生命游戏中活细胞的数量。目标是查看一个 int 列表列表,并在给定单元格坐标的情况下,返回其旁边的存活单元格的数量。
问题是我的函数似乎完全随机回答,我看不出是什么导致代码中出现
这种情况问题可能出在
这是我的代码:
(* nth : reimplementation of List.nth that returns 0 if there is no such
* element
* [int list -> int -> int] *)
let rec nth l n =
match l with
| [] -> 0
| a::l -> if n = 0
then a
else nth l (n-1);;
(* get_cell : given a couple of coordinates, returns the value at the
* coordinates on the matrix
* [int * int -> int list list -> int] *)
let rec get_cell (x,y) matrix =
match (List.nth matrix y) with
| [] -> empty
| l -> nth l x;;
(* count_neighbours : given a couple of coordinates and a matrix, returns the
* number of alive cells in the neighborhood of the designed cell
* [int * int -> int list list -> int] *)
let count_neighbours (x,y) matrix =
let neighbors = [ (x-1,y-1); (x-1,y); (x-1,y+1);
(x,y-1); (x,y+1);
(x+1,y-1); (x+1,y); (x+1,y+1); ] in
let rec aux = (function
| [] -> 0
| h::t -> (get_cell h matrix) + aux (t)
) in
aux neighbors;;
这是一个示例会话:
# let test_board = [[0; 1; 1; 1; 1]; [1; 0; 0; 0; 0]; [1; 0; 1; 0; 0]; [0; 1; 0; 0; 0];
[0; 1; 1; 0; 1]];;
val test_board : int list list =
[[0; 1; 1; 1; 1]; [1; 0; 0; 0; 0]; [1; 0; 1; 0; 0]; [0; 1; 0; 0; 0];
[0; 1; 1; 0; 1]]
# count_neighbours (3,3) test_board;;
- : int = 3
# get_cell (2,2) test_board;;
- : int = 1
# get_cell (2,3) test_board;;
- : int = 0
# get_cell (2,4) test_board;;
- : int = 1
# get_cell (3,2) test_board;;
- : int = 0
# get_cell (3,4) test_board;;
- : int = 0
# get_cell (4,2) test_board;;
- : int = 0
# get_cell (4,3) test_board;;
- : int = 0
# get_cell (4,4) test_board;;
- : int = 1
如您所见,随机结果...感谢您的帮助。