Lisp の複数の if ステートメントについて質問があります。count
が等しくない場合はandステートメントn
を続行し、それ以外の場合は実行し、それがnil を返します。let
if
(= (abs (- row i))
t
ただし、常にブロック内のコードの最後の行を返すため、そうcount
でない場合はいつでも戻ることがわかりました。ではない場合にのみ、句のいずれかが である場合にのみ戻るようにプログラムを作成する方法を教えてください。n
nil
progn
count
n
nil
or
t
(loop for i below n
do (if (/= count n)
(progn
(let ((tcol (getqueencol i n)))
(if (or (= col tcol) (= (abs (- row i)) (abs (- col tcol))))
(return-from queen-can-be-placed-here nil))))
(if (= (abs (- row i)))
(return-from queen-can-be-placed-here nil))))
更新しました:
良い反応をありがとう。はい、確かに私は N クイーン パズルを解こうとしています :P 私が現在抱えている問題は、特定の行と列にクイーンを配置するかどうかを決定するコントロールが、行が空のときに機能しないことです。これは、行が空のときにgetqueencol
が返され、そこに.nil
queen-can-be-placed-here
(= nil NUMBER)
これに対抗するために、行が空かどうかを知るカウント変数を作成しようとしました。これにより、空の行queen-can-be-placed-here
を呼び出さないようgetqueencol
にすることができます。queen-can-be-placed-here
問題は、クイーンが空の行に追加されるときにチェックがどのようになるかわからないことです。
これまでのコードは次のとおりです。
(defvar *board* (make-array '(5 5) :initial-element nil))
(defun getqueencol (row n)
"Traverses through the columns of a certain row
and returns the column index of the queen."
(loop for i below n
do (if (aref *board* row i)
(return-from getqueencol i))))
(defun print-board (n)
"Prints out the solution, e.g. (1 4 2 5 3),
where 1 denotes that there is a queen at the first
column of the first row, and so on."
(let ((solutionlist (make-list n)))
(loop for row below n
do (loop for col below n
do (when (aref *board* row col)
(setf (nth row solutionlist) col))))
(print solutionlist)))
(defun queen-can-be-placed-here (row col n)
"Returns t if (row,col) is a possible place to put queen, otherwise nil."
(let ((count 0))
(loop for i below n ;This is the block I added to keep track of if a row is empty (count = n)
do (if (not (aref *board* row i))
(setf count (+ 1 count))))
(loop for i below n
do (if (/= count n)
(let ((tcol (getqueencol i n)))
(if (or (= col tcol) (= (abs (- row i)) (abs (- col tcol))))
(return-from queen-can-be-placed-here nil)))
(if (= (abs (- row i))) ;Here is where I don't know what to check
(return-from queen-can-be-placed-here nil)))))
(return-from queen-can-be-placed-here t))
(defun backtracking (row n)
"Solves the NxN-queen problem with backtracking"
(if (< row n)
(loop for i below n
do (when (queen-can-be-placed-here row i n)
(setf (aref *board* row i) 't)
(backtracking (+ row 1) n)
(setf (aref *board* row i) 'nil)))
(print-board n)))
(defun NxNqueen-solver (k)
"Main program for the function call to the recursive solving of the problem"
(setf *board* (make-array (list k k) :initial-element nil))
(backtracking 0 k))