I am trying to make combinations (Please let me know if the terminology that I am using can be improved), such that we every element of the result list is a combination of two input lists, and the result list covers all the possible combinations.
The elements are not allowed to move around, the the first element of a sublist is first element of either input List, the second element of a sublist is second element of either sublist, and so on..
Example 1:
Input: List(1,1,1)
and List(0,0,0)
(we can assume that lists have same length)
Output:
List(List(1, 1, 1),
List(1, 1, 0),
List(1, 0, 1),
List(0, 1, 1),
List(1, 0, 0),
List(0, 1, 0),
List(0, 0, 1),
List(0, 0, 0))
Example 2:
Input: List(1,2,3)
and List(4,5,6)
Output:
List(List(1, 2, 3),
List(1, 2, 6),
List(1, 5, 3),
List(1, 5, 6),
List(4, 5, 6),
List(4, 5, 3),
List(4, 2, 3),
List(4, 2, 6))
My current solution only works on the simple case (Example 1):
def makeCombinations(a: List[Int], b: List[Int]): List[List[Int]] = {
val N = a.length
(0 to N).map(x => a.slice(x, N) ::: b.slice(0, x)).flatMap(x => x.permutations).toList
}
What is the best way to approach this?
I am not looking to find a cross product
, which would result in:
List(List(1, 4),
List(1, 5),
List(1, 6),
List(2, 4),
List(2, 5),
List(2, 6),
List(3, 4),
List(3, 5),
List(3, 6))
This questions is different from: Cross product in Scala