Search code examples
clojureclojure-contrib

Combining vectors by index


I am looking to write a function which inputs two vectors of length n,

i.e. [:a :b :c :d :e :f] [1 2 3 4 5 6]. Outputting one vector of length 2n

[:a 1 :b 2 :c 3 :d 4 :e 5 :f 6].

However, if the second vector being input doesn't match the length of n it will cycle,

i.e. [:a :b :c :d :e :f] [1 2 3]

outputs: [:a 1 :b 2 :c 3 :d 1 :e 2 :f 3].

 (defn Swanson [x y] (vec (flatten (interleave x (repeat (count x) y)))))

Moreover, the function can also take [x y min max n], where x and y are vectors, min is an index to start the interleaving, max is an index to end the interleaving, and n is a step-size for the interleaving.


Solution

  • With x and y vectors, min the (inclusive) starting index, max the (exclusive) ending index, n the step size:

    (defn swanson [x y min max n]
      (->> (interleave x (cycle y))
           (take max)
           (drop min)
           (take-nth n)))