DEV Community

Discussion on: 6-10PM challenge problem #002

Collapse
 
larisho profile image
Gab

Clojure solution

Note: This solution is O(n) because (apply * list) expands into (* list0 list1 ... listn)

(defn rest-vec [lst]
  "`rest` that returns a vector instead of a list"
  (into [] (rest lst)))

(defn array-of-products [arr]
  "Calculates product of everything but the first 
element and then moves the first element to the end and loops"
  (loop [lst arr
         time 0
         res []]
    (if (>= time (count lst))
      res
      (recur (conj (rest-vec lst) (first lst)) 
             (inc time) 
             (conj res (apply * (rest lst)))))))

(array-of-products [8 10 2])
;; [20 16 80]
(array-of-products [2 7 4 3])
;; [84 24 42 56]