说我有这样的一套:
#{"word1" "word2" "word3"}
我怎样才能列出这些单词的所有订购方式,即
word1 word2 word3
word2 word3 word1
word3 word2 word1
等
答案 0 :(得分:13)
最简单的方法是使用math.combinatorics:
user> (require '[clojure.math.combinatorics :as combo])
nil
user> (combo/permutations #{"word1" "word2" "word3"})
(("word1" "word2" "word3") ("word1" "word3" "word2") ("word2" "word1" "word3") ("word2" "word3" "word1") ("word3" "word1" "word2") ("word3" "word2" "word1"))
编辑:我还没看过math.combinatorics的实现,但是这里有一个懒惰的版本,因为OP要求提供一些代码。
(defn permutations [s]
(lazy-seq
(if (seq (rest s))
(apply concat (for [x s]
(map #(cons x %) (permutations (remove #{x} s)))))
[s])))
答案 1 :(得分:7)
虽然math.combinatorics可能是正确答案,但我一直在寻找更简单的方法。以下是我可以遵循的非惰性实现:
(defn permutations [colls]
(if (= 1 (count colls))
(list colls)
(for [head colls
tail (permutations (disj (set colls) head))]
(cons head tail))))