开发者

creating overlapping vectors in clojure

Given several vectors, what's the best way to create new vectors that ove开发者_StackOverflow社区rlap 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]


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))


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)))))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜