2013-04-14 126 views
2

因此,我使用Lisp製作了一個相對簡單的遊戲。將項目放置在2D矩陣列中的第一個零元素

我創建了一個董事會指定大小的所有元素NIL:

(defun make-board(rows columns) 
    (cond ((= rows 1) (list (make-list columns))) 
     (t (append (list (make-list columns)) (make-board (1- rows) columns))))) 

現在我工作的地方的功能,將在二維表的列的第一個nil元素放置一個值:

(defun place(player column matrix) 
    ;need some help here 

    ;I can get the specified column, is there a better way?! 
    (let (col)(get-column column matrix)) 
) 

我可以檢索指定列:

; return the given column 
(defun get-column 
    (colnum matrix) 
    (mapcar (lambda (row) (nth colnum row)) matrix)) 

我喜歡這種感覺是S但不幸的是,Lisp對我來說工作不好。我也喜歡這個沒有迭代的實現,因爲這是做Lisp的「正確」方式。

編輯:

爲了澄清,使板將返回類似如下:

(make-board 5 5) 
((NIL NIL NIL NIL NIL) 
(NIL NIL NIL NIL NIL) 
(NIL NIL NIL NIL NIL) 
(NIL NIL NIL NIL NIL) 
(NIL NIL NIL NIL NIL)) 
+0

爲什麼標記爲'Emacs'? Emacs Lisp中的代碼是? –

回答

1

我不知道爲什麼遞歸性應該是「正確」的方式用Lisp編程。循環宏是非常有用的,像你想要實現的功能可以很容易地實現它。

(defun make-board(rows columns) 
    (loop repeat rows collect 
    (loop repeat columns collect nil))) 
0

我相信,這將是使用您的主板二維數組更方便:

(defun make-board (rows columns) 
    (make-array (list rows columns) 
       :initial-element nil)) 

爲了找到一列的第一個空單元格,遍歷該列:

(defun find-null-cell-index (column board) 
    "Returns the row index of the first cell in the given column of the board 
that contains nil." 
    (loop :for i :below (array-dimension board 0) 
     :when (null (aref board i column)) 
     :do (return-from find-null-cell-index i))) 
相關問題