给定几个向量,创建由一个元素重叠的新向量的最佳方法是什么?
例如,给定这些向量:
[1 1 1] [2 2 2] [3 3 3]
得到的重叠向量将是:
[1 1 1 2]
[1 2 2 2 3]
[2 3 3 3]
答案 0 :(得分:2)
我的策略是:
由于需要处理开始和结束条件,代码有点复杂,但您可以使用以下内容执行此操作:
(def vectors [[1 1 1] [2 2 2] [3 3 3]])
(map
#(concat
(if (last %1) [(last %1)] [])
%2
(if (first %3) [(first %3)] []))
(cons nil (butlast vectors))
vectors
(concat (rest vectors) [nil]))
=> ((1 1 1 2) (1 2 2 2 3) (2 3 3 3))
答案 1 :(得分:1)
递归实现:
(defn overlap [colls]
(loop [ret [] prefix [] x (first colls) colls (next colls)]
(if colls
(recur (conj ret (concat prefix x [(ffirst colls)])) [(last x)] (first colls) (next colls))
(conj ret (concat prefix x)))))