jhickner
jhickner

Reputation: 1053

creating overlapping vectors in clojure

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

Answers (2)

Jürgen Hötzel
Jürgen Hötzel

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

mikera
mikera

Reputation: 106351

My strategy would be:

  • Create three sequences of vectors, each offset by one (forwards and backwards)
  • Map through these three sequences, concatenating the last and first elements of the preceeding and succeeding vector with all of the current vector

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

Related Questions