2013-10-13 79 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' 請糾正我,如果我錯了,但看起來我們不是在看相同的對角線... –