如何在Clojure中找到此向量的最小成员的索引?

kos*_*tas 5 reduce clojure

我使用以下表达式来检索向量中最小数字的索引.但是,我想避免使用.indexOf(出于效率原因和数字精度,尽管我猜数字是隐式转换为字符串).

(.indexOf [1 2 3 4 0 5]
  (reduce #(if (< %1 %2) %1 %2) [1 2 3 4 0 5] ))
Run Code Online (Sandbox Code Playgroud)

是否可以使用reduce进行不同的操作?

Ale*_*art 15

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


mik*_*era 6

如果您想有效地执行此操作,我建议使用 loop/recur,可能类似于以下内容:

(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))))
Run Code Online (Sandbox Code Playgroud)

这个想法是遍历整个向量,跟踪到目前为止在每个点找到的最小值和最小值的索引。