2013-10-13 83 views
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 

正如你所看到的,随机结果... 感谢您的帮助。

回答

1

据我所知,这不是一个完全随机,除非您指定的随机性。 :-)

我敢肯定它的使用权只是一个次要的事情坐标,让你的细胞。既然你已经提到这是一项家庭作业,我只是指出你得到解决方案,而不是一句谚语。

是什么List.nth test_board x给你? x是您在上面输入的任何数字。

做一些小的调整后,雷给了我这样的结果:

# get_cell (2,4) test_board;; 
- : int = 0 
# count_neighbours (3,3) test_board;; 
- : int = 3 

好运。

编辑 对于count_neighbours实施,如果你把它看作是一个列表的列表,如下图所示帮助。

把你test_board,它看起来像这样的OCAML编译:

0 1 2 3 4 
0 [0; 1; 1; 1; 1]; 
1 [1; 0; 0; 0; 0]; 
2 [1; 0; 1; 0; 0]; 
3 [0; 1; 0; **0**; 0]; 
4 [0; 1; 1; 0; 1]; 

我强调对应(3, 3)细胞。在那里显示三个1 - 左上角,左下角和右下角。

+0

感谢您的输入,但我很困惑: '#count_neighbours(3,3)test_board ;;' 不应该返回 ' - :INT = 3' 而是 ' - :int = 1' 如果我没有弄错。 –

+0

这是因为沿对角线有3'1'到单元格'(3,3)'。看看你的'count_neighbours'的实现以及你如何构建'neighours'列表。所以,一旦你得到所有'1',你只是把它们加起来。 –

+0

我知道这一点,但我似乎无法找到三个'1'。 对角线由'000 010 100' 请纠正我,如果我错了,但看起来我们不是在看相同的对角线... –