我想将一个排序整数数组划分为连续的分区。
以下红宝石:
[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 它只需要争论。
您必须将之前的元素保存在某处。在这种情况下,你可以这样做:
(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]]