我想我现在更好地理解了你想要列举的内容,所以这里是
您对替代定义的问题的另一个答案
一条“路径”:一条路径可以描述为一系列方向,
向下 (0) 或向下 (1)。那是微不足道的映射
为无符号整数 0 ≤ path path-directions
其中每一位代表连续的方向。每条路径都是
方便地由这对表示(path-directions,number)
其中path-directions 是方向数,number
对位 0 到 path-directions-1 中的连续方向进行编码。
(defun gen-paths (path-directions)
(loop for i below (expt 2 path-directions)
collect i))
(gen-paths 3) => (0 1 2 3 4 5 6 7)
(defun path-to-directions (path-directions path)
(loop for i downfrom (- path-directions 1) to 0
collect (elt #(:down :down-right)
(ldb (byte 1 i) path))))
(loop for path in (gen-paths 3) collect (path-to-directions 3 path)) =>
((:DOWN :DOWN :DOWN) (:DOWN :DOWN :DOWN-RIGHT)
(:DOWN :DOWN-RIGHT :DOWN) (:DOWN :DOWN-RIGHT :DOWN-RIGHT)
(:DOWN-RIGHT :DOWN :DOWN) (:DOWN-RIGHT :DOWN :DOWN-RIGHT)
(:DOWN-RIGHT :DOWN-RIGHT :DOWN) (:DOWN-RIGHT :DOWN-RIGHT :DOWN-RIGHT))
请注意,path-directions 比
三角形。当您将路径表示为节点列表时
有一个额外的元素,起始节点 (0, 0)。
(defun path-to-ref (path-directions path)
"Map a path to the list of (I J) pairs as understood by `get-node`."
(loop for i upto path-directions
for j = 0 then (+ j (ldb (byte 1 (- path-directions i)) path))
collect (list i j)))
(loop with path-directions = (- (length *test*) 1)
for path in (gen-paths path-directions)
collect (path-to-ref path-directions path))
=>
(((0 0) (1 0) (2 0) (3 0)) ((0 0) (1 0) (2 0) (3 1))
((0 0) (1 0) (2 1) (3 1)) ((0 0) (1 0) (2 1) (3 2))
((0 0) (1 1) (2 1) (3 1)) ((0 0) (1 1) (2 1) (3 2))
((0 0) (1 1) (2 2) (3 2)) ((0 0) (1 1) (2 2) (3 3)))
(defun get-path-nodes (path triangle)
"Returns the values of the nodes along PATH in TRIANGLE"
(loop with path-directions = (- (length triangle) 1)
for (i j) in (path-to-ref path-directions path)
collect (get-node i j triangle)))
然后您可以轻松获取值:
(loop with path-directions = (- (length *test*) 1)
for path in (gen-paths path-directions)
collect (get-path-nodes path *test*))
=>
((3 7 2 8) (3 7 2 5) (3 7 4 5) (3 7 4 9)
(3 4 4 5) (3 4 4 9) (3 4 6 9) (3 4 6 3))
或将它们相加
(loop with path-directions = (- (length *test*) 1)
for path in (gen-paths path-directions)
collect (loop for v in (get-path-nodes path *test*)
sum v))
=>
(20 17 19 23 16 20 22 16)