문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top