clojure - 列出列表的所有排列 [英] clojure - list all permutations of a list
本文介绍了clojure - 列出列表的所有排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个这样的集合:
Say I have a set like this:
#{"word1" "word2" "word3"}
我怎样才能列出这些单词的所有排序方式,即
How could I list all ways that these words might be ordered, i.e.
word1 word2 word3
word2 word3 word1
word3 word2 word1
等
推荐答案
最简单的方法是使用 math.组合学:
The easiest way is using 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 要求遵循一些代码.
I haven't looked at the math.combinatorics implementation, but here's a lazy version because OP asked for some code to follow.
(defn permutations [s]
(lazy-seq
(if (seq (rest s))
(apply concat (for [x s]
(map #(cons x %) (permutations (remove #{x} s)))))
[s])))
这篇关于clojure - 列出列表的所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文