让我们假设我有一个二维列表(如果你愿意,也可以是数组),如下所示:
'( (I I I O)
(I X I O)
(I I I O))
现在让我们假设我想找到 X 的所有邻居。在这种情况下,我的函数将返回一个包含 8 个 I:s 的列表。我将如何以一种聪明的方式实现这个功能?我已经实现了一个如下所示的功能:
(defun get-neighbours (board x y)
(let ((output '() ))
(push (get-if-possible board (1+ x) y) output)
(push (get-if-possible board (1- x) y) output)
(push (get-if-possible board x (1+ y)) output)
(push (get-if-possible board x (1- y)) output)
(push (get-if-possible board (1+ x) (1+ y)) output)
(push (get-if-possible board (1- x) (1- y)) output)
(push (get-if-possible board (1+ x) (1- y)) output)
(push (get-if-possible board (1- x) (1+ y)) output)
output))
那太……丑陋了。
最佳答案
准备了这样的东西:
(defconstant +neighbour-offsets+
'((-1 . -1) (0 . -1) (1 . -1)
(-1 . 0) (1 . 0)
(-1 . 1) (0 . 1) (1 . 1)))
然后你的函数可以像这样简单
(defun get-neighbours (board x y)
(mapcar (lambda (offs)
(let ((dx (car offs))
(dy (cdr offs)))
(get-if-possible board (+ x dx) (+ y dy))))
+neighbour-offsets+))
关于common-lisp - 在二维列表中寻找邻居,聪明的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5777495/