Search code examples
loopsclojurenon-recursive

Clojure multiply first n elements in sequence by 'x' non recursive


I am a newbie in clojure and came across a problem which says, multiply first n elements in a sequence by some number 'x' (non recursively). So for example

 (multiply-n-by-x [1 2 3 4 5] 2 10) => [10 20 30 4 5]

So here i understood that i need to loop over the sequence n times and then stop, but i am unable to do that. If someone could guide me on how to do about it, it would be great.


Solution

  • Same as Shawn's answer but with destructuring and split-at (a bit less redundant):

    (defn multiply-n-by-x [s n x]
      (let [[s1 s2] (split-at (inc n) s)]
        (concat (map #(* x %) s1) s2)))