在 clojure 中如何将已排序整数数组划分为连续的分区?

问题描述 投票:0回答:1

我想将一个排序整数数组划分为连续的分区。

以下红宝石:

[1,2,3,8,9,10,99].slice_when { |x, y| y > x + 1 }.to_a

输出:

[[1, 2, 3], [8, 9, 10], [99]]

如何在 Clojure 中执行此操作?

我尝试使用

partition-by
,但 AFAIK 它只需要争论。

ruby clojure
1个回答
1
投票

您必须将之前的元素保存在某处。在这种情况下,你可以这样做:

(defn split [coll]
  (let [prev (atom (first coll))]
    (->> coll
         (partition-by #(< (inc @prev) (reset! prev %))))))

(split [1 2 3 8 9 10 99])
=> ((1 2 3) (8 9 10) (99))

如果你也想提供那个功能,你将不得不写一些基于

reduce
的解决方案:

(defn slice-when [pred coll]
  (->> coll
       (reduce (fn [acc current]
                 (if-let [previous (peek (last acc))]
                   (if (pred previous current)
                     (conj acc [current])
                     (conj (pop acc) (conj (peek acc) current)))
                   (conj acc [current])))
               [])))

例子:

(slice-when (fn [x y] (> y (inc x))) 
            [1 2 3 8 9 10 99])
=> [[1 2 3] [8 9 10] [99]]
© www.soinside.com 2019 - 2024. All rights reserved.