algorithm - 如何在 Clojure 中将序列划分为递增的子序列?

标签 algorithm clojure

我有一个整数序列,我想将它们分成递增的段,并且我希望段数尽可能少。所以我想拥有

(segmentize [1 2 3 4 3 8 9 1 7] <=)
;=> [[1 2 3 4][3 8 9][1 7]]

我已经按如下方式实现了分段:

(defn segmentize [col lte]
  (loop [col col s [] res []]
    (cond (empty? col) (conj res s)
          (empty? s) (recur (rest col) (conj s (first col)) res)
          (lte (last s) (first col)) (recur (rest col) (conj s (first col)) res)
          :else (recur col [] (conj res s)))))

但我想知道是否已经有一些方便的 clojure 函数可以做到这一点,或者是否有更惯用的方法来做到这一点。

最佳答案

您可以构建this使用分区方式

(defn segmentize [cmp coll]
  (let [switch (reductions = true (map cmp coll (rest coll)))]
    (map (partial map first) (partition-by second (map list coll switch)))))

(segmentize <= [1 2 3 4 3 8 9 1 7])
;=> ((1 2 3 4) (3 8 9) (1 7))

如果你真的想要向量而不是惰性序列,最后一行的前两个 map 可以更改为 mapv

关于algorithm - 如何在 Clojure 中将序列划分为递增的子序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25121201/

相关文章:

json - 如何将json文件读入Clojure defrecord(稍后搜索)

java - Clojail 不会在 Clojure 中抛出安全异常

algorithm - 解析操作码的高效算法

java - 数组中第三小的元素

clojure - 核心逻辑: how to generate a repeated sequence of number?

java - 是否可以将树(数据结构)传递给 clojure 并对其进行处理?

clojure - 如何覆盖现有对象的方法?

algorithm - 寻找算法来寻找参数以满足给定函数的返回

python - 为什么冒泡排序比快速排序快

java - 如何将包含字符串和整数的文件读入 ArrayList 并按整数排序?