元素的组合

Kig*_*gyo 6 scala

问题:

给出一个Seq seq和一个Int n.

我基本上希望元素的所有组合都达到 n的大小.这种安排很重要,例如[1,2]与[2,1]不同.

def combinations[T](seq: Seq[T], size: Int) = ...
Run Code Online (Sandbox Code Playgroud)

例:

combinations(List(1,2,3), 0) 
//Seq(Seq())

combinations(List(1,2,3), 1)
//Seq(Seq(), Seq(1), Seq(2), Seq(3))

combinations(List(1,2,3), 2) 
//Seq(Seq(), Seq(1), Seq(2), Seq(3), Seq(1,2), Seq(2,1), Seq(1,3), Seq(3,1),
//Seq(2,3), Seq(3,2))

...
Run Code Online (Sandbox Code Playgroud)

到目前为止我所拥有的:

def combinations[T](seq: Seq[T], size: Int) = {
 @tailrec
  def inner(seq: Seq[T], soFar: Seq[Seq[T]]): Seq[Seq[T]] = seq match {
    case head +: tail => inner(tail, soFar ++ {
      val insertList = Seq(head)
      for {
        comb <- soFar
        if comb.size < size
        index <- 0 to comb.size
      } yield comb.patch(index, insertList, 0)
    })
    case _ => soFar
  }

  inner(seq, IndexedSeq(IndexedSeq.empty))
}
Run Code Online (Sandbox Code Playgroud)

你对这个问题有什么看法?这种方法将被大量调用,因此应该最有效.

库中的方法有subsets或者combinations(我选择了相同的名称),它们返回迭代器.我也考虑过这一点,但我还不知道如何设计这个懒惰.

Spi*_*Pig 6

不确定这是否足够有效,但这是最简单的方法.

def combinations[T](seq: Seq[T], size: Int) : Seq[Seq[T]] = {
  (1 to size).flatMap(i => seq.combinations(i).flatMap(_.permutations))
}
Run Code Online (Sandbox Code Playgroud)

编辑:为了使它变得懒惰你可以使用视图

def combinations[T](seq: Seq[T], size: Int) : Iterable[Seq[T]] = {
  (1 to size).view.flatMap(i => seq.combinations(i).flatMap(_.permutations))
}
Run Code Online (Sandbox Code Playgroud)