clojure-列出列表的所有排列
假设我有这样一套:clojure-列出列表的所有排列,clojure,Clojure,假设我有这样一套: #{"word1" "word2" "word3"} 我如何列出这些单词的所有排列方式,即 word1 word2 word3 word2 word3 word1 word3 word2 word1 等等。最简单的方法是使用: 编辑:我还没有看过math.combinations的实现,但是这里有一个懒惰的版本,因为OP需要一些代码 (defn permutations [s] (lazy-seq (if (seq (rest s)) (apply c
#{"word1" "word2" "word3"}
我如何列出这些单词的所有排列方式,即
word1 word2 word3
word2 word3 word1
word3 word2 word1
等等。最简单的方法是使用:
编辑:我还没有看过math.combinations的实现,但是这里有一个懒惰的版本,因为OP需要一些代码
(defn permutations [s]
(lazy-seq
(if (seq (rest s))
(apply concat (for [x s]
(map #(cons x %) (permutations (remove #{x} s)))))
[s])))
虽然math.Combinatics可能是正确的答案,但我一直在寻找更简单的方法。下面是我可以遵循的非惰性实现:
(defn permutations [colls]
(if (= 1 (count colls))
(list colls)
(for [head colls
tail (permutations (disj (set colls) head))]
(cons head tail))))
在尝试实现置换时,我得到了“ISeq from:experience.core$eval261$fn__262”。将其称为(println(置换)。是因为我不能打印惰性序列吗?
#(“w”“d”“m”)
是匿名函数的语法。你想要{w“d”m}
@stevemacnIs有没有理由认为(删除{x}s)
比(disj s x)
更受欢迎?
(defn permutations [colls]
(if (= 1 (count colls))
(list colls)
(for [head colls
tail (permutations (disj (set colls) head))]
(cons head tail))))