0

人生ゲームで生きている細胞の数を取得する関数を作成しようとしています。目標は、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

ご覧のとおり、ランダムな結果です...ご協力ありがとうございます。

4

1 に答える 1