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