因子的Scala排列

时间:2011-02-20 11:17:26

标签: scala

如何在Scala上找到某些字母的n!个排列?

2 个答案:

答案 0 :(得分:9)

Scala 2.9 RC1:

scala> "abc".permutations.toList
res58: List[String] = List(abc, acb, bac, bca, cab, cba)

答案 1 :(得分:8)

scala> def permutations[T](xs: List[T]): List[List[T]] = xs match {
     |     case Nil => List(Nil)
     |     case _   => for(x <- xs;ys <- permutations(xs diff List(x))) yield x::ys
     | }
permutations: [T](xs: List[T])List[List[T]]

scala> permutations("abc".toList) foreach println
List(a, b, c)
List(a, c, b)
List(b, a, c)
List(b, c, a)
List(c, a, b)
List(c, b, a)