Scala permutation of Factorials

前端 未结 2 1972
感动是毒
感动是毒 2021-01-23 20:25

How can I find the n! permutations of certain letters on Scala?

2条回答
  •  遥遥无期
    2021-01-23 20:52

    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)
    

提交回复
热议问题