Reputation: 159
I have written following code to return all possible combinations of Array of Integers
def findAllCombinations ( remain:Array[Int], partial:Array[Int],cum :List[Array[Int]]) : List[Array[Int]]= {
for ( i <- 0 until remain.size) {
val m = partial ++ Array(remain(i))
val n = m::cum
findAllCombinations(remain.slice(i+1 ,remain.size),m,n)
}
cum
}
When I call this function using following parameters I am getting empty list.
findAllCombinations(Array(1,2,3),Array(),List(Array()))
Can somebody help me in improving the code?
Upvotes: 0
Views: 233
Reputation: 2821
In your code, the for
causes invocations of findAllCombinations
but then it returns the cum
that the base invocation was called with, which is List(Array())
.
0 until remain.size
evaluates to a scala.collection.immutable.Range
for ( i <- 0 until remain.size) { ... }
evaluates to (0 until remain.size).foreach({ ... })
, which evaluates to Unit
(no matter what is done in the block)
cum
is returned anyways, from the base invocationIf you do not want permutations, but by "combinations" you mean "subsets" (i.e. get the power set of the original set):
def findAllCombinations(remain:Seq[Int]) : List[Seq[Int]]= {
remain match {
case head :: tail =>
val tailCombinations = findAllCombinations(tail)
tailCombinations.flatMap((combo: Seq[Int]) => Seq(head +: combo, combo))
case _ => List(Seq())
}
}
val x = findAllCombinations(Seq(1,2,3))
println(x)
println(x.length)
Output:
List(List(1, 2, 3), List(2, 3), List(1, 3), List(3), List(1, 2), List(2), List(1), List())
8
Upvotes: 2