algorithm - Clojure 组顺序出现 - 改进功能

标签 algorithm clojure

我试图将直接出现在彼此旁边的项目分组,只要它们都在给定的“白名单”中即可。分组必须至少包含两个或更多项目。

例如,第一个参数是集合,第二个参数是白名单。

(group-sequential [1 2 3 4 5] [2 3])
>> ((2 3))

(group-sequential ["The" "quick" "brown" "healthy" "fox" "jumped" "over" "the" "fence"] 
                  ["quick" "brown" "over" "fox" "jumped"])
>> (("quick" "brown") ("fox" "jumped" "over"))

(group-sequential [1 2 3 4 5 6 7] [2 3 6])
>> ((2 3))

这是我想出的:

(defn group-sequential
  [haystack needles]
  (loop [l haystack acc '()]
    (let [[curr more] (split-with #(some #{%} needles) l)]
      (if (< (count curr) 2)
        (if (empty? more) acc (recur (rest more) acc))
        (recur (rest more) (cons curr acc))))))

它可以工作,但是非常丑陋。我想知道在 Clojure 中是否有更简单的惯用方法? (在我发现 split-with 之前你应该已经看到了 fn :)

我打赌有一个很好的单行代码,带有分区或其他东西,但已经晚了,我似乎无法让它工作。

最佳答案

(defn group-sequential [coll white] 
  (->> coll
       (map (set white))
       (partition-by nil?)
       (filter (comp first next))))

... Diego Basch's method 的更简洁版本。

关于algorithm - Clojure 组顺序出现 - 改进功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26352385/

相关文章:

algorithm - 谜题:N个人坐在圆 table 上。没有交叉任何其他握手的握手方式

Clojure/FP : apply functions to each argument to an operator

Clojure:如何在 project.clj 中设置 :repositories

json - 在 Clojure 中使用 Amazonica 时,应该如何格式化 Kinesis 事件的数据?

algorithm - 在 log(n) 时间内排序的 bool n*n 矩阵中 0 的数量

algorithm - 确定给定的集合是否可以划分为两个子集,使得两个子集中的元素之和相同

c++ - 显示属于树的深度路径的二叉搜索树的节点

macros - Clojure 中尚未提供的简单而引人注目的宏示例

clojure - 如何对一系列 lvar 进行操作

algorithm - 分而治之算法应用于查找数组中的峰值。