Clojure: Increment first element of every vector in list

Viewed 180

I have a list of vectors like this:

([4 0] [4 2] [2 1] [4 1])

How can i increment the first element of every vector by a certain value X ?

desired output:

([5 0] [5 2] [3 1] [5 1])

This is my current approach, but i think i could be much simpler:

(defn shiftVector [oldVector number]
   (map vector
      (map #(+ (first %) number) oldVector )
      (map  #(second %) oldVector))
)
3 Answers

Since vectors are associative on their indices, probably the simplest approach is:

(defn shift-vector [v n]
  (map #(update % 0 + n) v))

(shift-vector [[4 0] [4 2] [2 1] [4 1]] 1)
;=> ([5 0] [5 2] [3 1] [5 1])

This works with any length vectors in the list (except empty vectors but then you couldn't increment those anyway).

Extract the first element, increment it, then put everything back into a new vector:

(defn inc-first [col]
  (map #(into [] (flatten (conj [] (inc (first %)) (rest %)))) col))

Tests:

user=> (inc-first '([4 0] [4 2] [2 1] [4 1]))
([5 0] [5 2] [3 1] [5 1])
user=> (inc-first '([4 0 0] [4 2 2] [2 1 1] [4 1 1]))
([5 0 0] [5 2 2] [3 1 1] [5 1 1])
user=> (inc-first '([4 4 4 4] [4 2 2 2] [2 2 3 4] [4 1 0 -1]))
([5 4 4 4] [5 2 2 2] [3 2 3 4] [5 1 0 -1])

Use map.

;this solution works only for vectors of size 2

(defn inc-lst [lst x]
  (map (fn [e] (vector (+ (first e) x) (second e))) 
  lst))

(inc-lst '([4 0] [4 2] [2 1] [4 1]) 1)

;more general solution, works for vectors of size >= 1

(defn inc-lst2 [lst x]
  (map (fn [e] (apply vector (+ (first e) x) (rest e))) 
  lst))

(inc-lst2 '([4 0 0] [4 2 2] [2 1 1] [4 1 1]) 1)
(inc-lst2 '([4] [4] [2] [4]) 1)
Related