Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala function to get all sorted subsets of size k

I am given a set of size L and want to generate every sorted subset of size k. Would be great if your solution is in scala but maybe I am able to translate by myself.

An example run for L = 6 and k = 3 should yield.

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

My scala attempt was something like:

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))
    }
  }
}

I hope you can help me.

like image 280
peri4n Avatar asked Dec 03 '22 06:12

peri4n


2 Answers

All you need is

def subsets(L: Int, k: Int) =  
  1 to L combinations k

Results:

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)

as required.

like image 192
Luigi Plinge Avatar answered Jan 13 '23 14:01

Luigi Plinge


You could start from that

def subsets(start: Int, end: Int, count: Int) :Seq[Seq[Int]] = (
  if (count == 0) 
    List(Nil)
  else 
    for(head <- start to end; tail <- subsets(head + 1, end, count -1)) 
    yield head +: tail
)
like image 26
Didier Dupont Avatar answered Jan 13 '23 15:01

Didier Dupont