clojure - 列出列表的所有排列

dag*_*da1 5 clojure

说我有这样的一套:

#{"word1" "word2" "word3"}
Run Code Online (Sandbox Code Playgroud)

我怎么能列出这些单词可能被命令的所有方式,即

word1 word2 word3
word2 word3 word1
word3 word2 word1
Run Code Online (Sandbox Code Playgroud)

等等

Die*_*sch 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"))
Run Code Online (Sandbox Code Playgroud)

编辑:我没有看过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])))
Run Code Online (Sandbox Code Playgroud)


dag*_*da1 7

虽然math.combinatorics可能是正确的答案,但我一直在寻找更简单的方法.以下是我可以遵循的非惰性实现:

(defn permutations [colls]
  (if (= 1 (count colls))
    (list colls)
    (for [head colls
          tail (permutations (disj (set colls) head))]
      (cons head tail))))
Run Code Online (Sandbox Code Playgroud)