Scala函数用于获取大小为k的所有已排序子集

per*_*i4n 4 scala function sorted permutation

我给了一组大小为L,并希望生成大小为k的每个已排序子集.如果您的解决方案是scala但是我可以自己翻译,那将会很棒.

应该产生L = 6和k = 3的示例运行.

1,2,3
1,2,4
1,2,5
1,2,6
1,3,4
1,3,5
1,3,6
1,4,5
1,4,6
1,5,6
2,3,4
2,3,5
2,3,6
2,4,5
2,4,6
2,5,6
3,4,5
3,4,6
3,5,6
4,5,6

我的scala尝试类似于:

object Util {
  def main(args : Array[String]) : Unit = {
    starts(6,3,1)
  }

  def starts(L: Int, num: Int, level: Int) : List[List[Int]] = {
    if( num == 0 ) {
      return List()
    }else{
      (level to (L-num+1)).map( o => o :: starts(L,num-1,level+1))
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望你能帮助我.

Lui*_*hys 14

所有你需要的是

def subsets(L: Int, k: Int) =  
  1 to L combinations k
Run Code Online (Sandbox Code Playgroud)

结果:

scala> subsets(6, 3) foreach println
Vector(1, 2, 3)
Vector(1, 2, 4)
Vector(1, 2, 5)
Vector(1, 2, 6)
Vector(1, 3, 4)
Vector(1, 3, 5)
Vector(1, 3, 6)
Vector(1, 4, 5)
Vector(1, 4, 6)
Vector(1, 5, 6)
Vector(2, 3, 4)
Vector(2, 3, 5)
Vector(2, 3, 6)
Vector(2, 4, 5)
Vector(2, 4, 6)
Vector(2, 5, 6)
Vector(3, 4, 5)
Vector(3, 4, 6)
Vector(3, 5, 6)
Vector(4, 5, 6)
Run Code Online (Sandbox Code Playgroud)

按要求.