假设我有一个这样的集合:
#{"word1" "word2" "word3"}
我怎样才能列出这些单词可能排序的所有方式,即
word1 word2 word3
word2 word3 word1
word3 word2 word1
etc.
最简单的方法是使用数学组合学:
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])))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)