所有使用scala重复的排列

per*_*i4n 8 combinations scala combinatorics repeat

我正在寻找scala方式来给出所有排列而不重复.我知道这个网站上已有一些帖子,但它们似乎有一个稍微不同的问题.

我正在寻找重复的所有排列.例如:

combine(List('A','C','G'))
Run Code Online (Sandbox Code Playgroud)

应该产量:

List(List('A'.'A','A'),List('A'.'A','C'),List('A'.'A','G'),List('A'.'C','A'),
List('A'.'C',''C), ... List('G'.'G','G')
Run Code Online (Sandbox Code Playgroud)

如果我的问题已经解决但我无法找到,我很抱歉.

提前致谢.

编辑:

我自己的方法(不编译):

def combine(size: Int = sym.length) : List[List[T]] = {
  size match {
    case 0 => List()
    case 1 => sym.toList.map(List(_))
    case _ => for (el <- sym) yield el :: combine(size-1)
  }
}
Run Code Online (Sandbox Code Playgroud)

sym是一个类的数组成员,它包含要组合的所有符号.

mis*_*tor 12

使用Scalaz:

scala> import scalaz._
import scalaz._

scala> import Scalaz._
import Scalaz._

scala> def combine[A](xs: List[A]): List[List[A]] = {
     |   xs.replicate[List](xs.size).sequence
     | }
combine: [A](xs: List[A])List[List[A]]

scala> combine(List('A', 'C', 'G'))
res47: List[List[Char]] = List(List(A, A, A), List(A, A, C), List(A, A, G), List
(A, C, A), List(A, C, C), List(A, C, G), List(A, G, A), List(A, G, C), List(A, G
, G), List(C, A, A), List(C, A, C), List(C, A, G), List(C, C, A), List(C, C, C),
 List(C, C, G), List(C, G, A), List(C, G, C), List(C, G, G), List(G, A, A), List
(G, A, C), List(G, A, G), List(G, C, A), List(G, C, C), List(G, C, G), List(G, G
, A), List(G, G, C), List(G, G, G))
Run Code Online (Sandbox Code Playgroud)


ham*_*mar 8

def combinations(size: Int = sym.length) : List[List[T]] = {
    if (size == 0)
        List(List())
    else {
        for {
            x  <- sym.toList
            xs <- combinations(size-1)
        } yield x :: xs
    }
}
Run Code Online (Sandbox Code Playgroud)


soc*_*soc 8

这应该工作:

val input = List('A','C','G')

(input ++ input ++ input) combinations(3) toList
Run Code Online (Sandbox Code Playgroud)