common-lisp - 在二维列表中寻找邻居,聪明的方式

标签 common-lisp

让我们假设我有一个二维列表(如果你愿意,也可以是数组),如下所示:

'( (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/

相关文章:

lambda - 如何在 lisp 中本地定义一个函数?

qt - Qt + Lisp 有什么好的实现吗?

cocoa - 使用 Mac 端口 Clozure Common Lisp 无法执行 `(require "COCOA")`

javascript - 如何从 JSCL 方法调用 Common Lisp 代码

lisp - 从嵌套列表中删除

decimal - 常见的 lisp 整数到十六进制转换

lisp - make-symbol 向生成的符号添加不需要的格式

list - 在 Common Lisp 中获取列表的前 n 个元素?

windows - 在 Windows 10 上安装 Quicklisp 时,我应该将 ~/.config/common-lisp/source-registry.conf.d/projects.conf 放在哪里以便 ASDF 查找?

common-lisp - 让 Hunchentoot 完全不输出 header