How can I find the index of the smallest member of this vector in Clojure?
user=> (first (apply min-key second (map-indexed vector [1 2 4 0 5]))) 3
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.
You can also use reduce
:
(def v [1 2 3 4 0 5])
(second (reduce (fn [[curr-min min-idx curr-idx] val]
(if (< val curr-min)
[val curr-idx (inc curr-idx)]
[curr-min min-idx (inc curr-idx)])) [(first v) 0 0] v)) ;; => 4
The result of reduce
is actually a three-element vector consisting of the minimum value, its index, and an index tracker (which is not important), respectively. And it traverses the collection once.
The initial value provided to reduce
is basically the first element of the collection.
I know the question is old, but it is here for posterity's sake.