clojure - 列出列表的所有排列 [英] clojure - list all permutations of a list

查看:126
本文介绍了clojure - 列出列表的所有排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这样的集合:

 #{word1word2word3} 

如何列出这些字可能排序的所有方式,例如

  word1 word2 word3 
word2 word3 word1
word3 word2 word1

$最简单的方法是使用 /github.com/clojure/math.combinatorics/\"> math.combinatorics

  user> (require'[clojure.math.combinatorics:as combo])
nil
user> (组合/排列#{word1word2word3})
((word1word2word3)(word1word3word2) word3)(word2word3word1)(word3word1word2)(word3word2word1))



编辑:我没有看过math.combinatorics的实现,但是这里是一个惰性版本,因为OP要求一些代码。

 (defn permutations [s] 
(lazy-seq
(if(seq(rest s))
(应用连接(for [xs]
(map#(cons x%)(permutations(remove#{x} s))))
[s]))


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

etc.

解决方案

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"))

Edit: 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆