Question

I have used the following expression to retrieve the index of the smallest number in a vector. However, I would like to avoid the use of .indexOf (for efficiency reasons and maybe numeric precision, although I guess the numbers are implicitly converted to strings).

(.indexOf [1 2 3 4 0 5]
  (reduce #(if (< %1 %2) %1 %2) [1 2 3 4 0 5] ))

Would it be possible to do it differently using reduce?

Was it helpful?

Solution

user=> (first (apply min-key second (map-indexed vector [1 2 4 0 5])))
3

OTHER TIPS

I'd suggest using loop/recur if you want to do this efficiently, perhaps something like the following:

(defn min-index [v] 
  (let [length (count v)]
    (loop [minimum (v 0)
           min-index 0
           i 1]
      (if (< i length)
        (let [value (v i)]
          (if (< value minimum)
            (recur value i (inc i))
            (recur minimum min-index (inc i))))
        min-index))))

The idea is to iterate across the whole vector, keeping track of the minimum and the index of the minimum value found so far at each point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top