我很难展开这个函数结果的嵌套结构。我认为它正确地执行了遍历,但是结果是嵌套的。
该函数尝试遍历列表,并在列表中查找所有可能的路径,其中相邻元素之间的数值距离为1、2或3。例如,从第一个元素1到下一个元素4,只需3步即可工作。但是,下一步我们可以从4跳到5跳1,从4跳到6跳2(跳5),或者从4跳到7跳3(跳5和6)。
我的问题有两个: 1)我能做些什么来防止深巢的发生?第二,是否有一种不同的方式来构造代码,以防止深层嵌套?
(def l0 (1 4 5 6 7 10 11 12 15 16 19 22))
(defn next-path-with-step [chain step]
(let [looking-at (first chain)
next-path (drop-while (fn [a]
(not (= (- a looking-at) step)))
chain)]
(if (empty? next-path)
nil
next-path)))
(defn find-chains [chains prefix]
(if (empty? chains)
prefix
(map (fn [chain]
(let [head (first chain)
next-paths (filter #(not (nil? %))
(map (partial next-path-with-step chain) [1 2 3]))]
(find-chains next-paths (conj prefix head))))
chains)))要运行它:
(find-chains [l0] [])我得到以下结果:
(((((((((((([1 4 5 6 7 10 11 12 15 16 19 22]))))) (((([1 4 5 6 7 10 12 15 16 19 22]))))))) ((((((([1 4 5 7 10 11 12 15 16 19 22]))))) (((([1 4 5 7 10 12 15 16 19 22]))))))) (((((((([1 4 6 7 10 11 12 15 16 19 22]))))) (((([1 4 6 7 10 12 15 16 19 22]))))))) ((((((([1 4 7 10 11 12 15 16 19 22]))))) (((([1 4 7 10 12 15 16 19 22])))))))))我想得到的是作为一个列表的内部序列。类似于:
([1 4 5 6 7 10 11 12 15 16 19 22]
[1 4 5 6 7 10 12 15 16 19 22]
[1 4 5 7 10 11 12 15 16 19 22]
[1 4 5 7 10 12 15 16 19 22]
[1 4 6 7 10 11 12 15 16 19 22]
[1 4 6 7 10 12 15 16 19 22]
[1 4 7 10 11 12 15 16 19 22]
[1 4 7 10 12 15 16 19 22])发布于 2020-12-11 15:53:25
以下是一些小小的改变,这将为您解决这一问题:
(defn find-chains [chains prefix]
(if (empty? chains)
[prefix] ;; return chain wrapped in a vector to avoid flattening
;; use mapcat instead of map to flatten internal find-chains calls
(mapcat (fn [chain]
(let [head (first chain)
next-paths (filter #(not (nil? %))
(map (partial next-path-with-step chain) [1 2 3]))]
(find-chains next-paths (conj prefix head))))
chains)))
user> (find-chains [l0] [])
;;=> ([1 4 5 6 7 10 11 12 15 16 19 22]
;; [1 4 5 6 7 10 12 15 16 19 22]
;; [1 4 5 7 10 11 12 15 16 19 22]
;; [1 4 5 7 10 12 15 16 19 22]
;; [1 4 6 7 10 11 12 15 16 19 22]
;; [1 4 6 7 10 12 15 16 19 22]
;; [1 4 7 10 11 12 15 16 19 22]
;; [1 4 7 10 12 15 16 19 22])https://stackoverflow.com/questions/65254371
复制相似问题