0
处理我试图做出让我活细胞的数目在生活的游戏功能时,随机的答案。 目标是查看一个int列表列表,并在给定单元格的坐标的情况下,返回其旁边的活动单元格的数量。
的问题是,我的功能似乎完全随机回答,我看不出有什么可以在代码
这是一个课堂作业导致此,所以我不要求一个明确的答案,只是一个提示,那里的问题可能在于与列表OCaml中
这里是我的代码:
(* 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
正如你所看到的,随机结果... 感谢您的帮助。
感谢您的输入,但我很困惑: '#count_neighbours(3,3)test_board ;;' 不应该返回 ' - :INT = 3' 而是 ' - :int = 1' 如果我没有弄错。 –
这是因为沿对角线有3'1'到单元格'(3,3)'。看看你的'count_neighbours'的实现以及你如何构建'neighours'列表。所以,一旦你得到所有'1',你只是把它们加起来。 –
我知道这一点,但我似乎无法找到三个'1'。 对角线由'000 010 100' 请纠正我,如果我错了,但看起来我们不是在看相同的对角线... –