gpt4 book ai didi

Clojure:查找重复

转载 作者:行者123 更新时间:2023-12-02 11:24:58 26 4
gpt4 key购买 nike

假设我们有一个整数列表:1, 2, 5, 13, 6, 5, 7,我想找到第一个重复的数字并返回两个索引的向量。在我的示例中,[2, 5] 处的值为 5。到目前为止我所做的是循环,但是我可以做得更优雅、更短吗?

(defn get-cycle
[xs]
(loop [[x & xs_rest] xs, indices {}, i 0]
(if (nil? x)
[0 i] ; Sequence is over before we found a duplicate.
(if-let [x_index (indices x)]
[x_index i]
(recur xs_rest (assoc indices x i) (inc i))))))

不需要返回数字本身,因为我可以通过索引获取它,其次,它可能并不总是存在。

最佳答案

使用列表处理的选项,但没有明显更简洁:

(defn get-cycle [xs]
(first (filter #(number? (first %))
(reductions
(fn [[m i] x] (if-let [xat (m x)] [xat i] [(assoc m x i) (inc i)]))
[(hash-map) 0] xs))))

关于Clojure:查找重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19894216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com