Reputation: 1053
Given several vectors, what's the best way to create new vectors that overlap by one element?
For example, given these vectors:
[1 1 1] [2 2 2] [3 3 3]
The resulting overlapped vectors would be:
[1 1 1 2]
[1 2 2 2 3]
[2 3 3 3]
Upvotes: 1
Views: 218
Reputation: 19727
A recursive implementation:
(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)))))
Upvotes: 1
Reputation: 106351
My strategy would be:
The code is slightly complicated by the need to handle the beginning and end conditions, but you could do it with something like:
(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))
Upvotes: 2