Scala permutations using two lists

What would be the best way to achieve the following, please? I have two lists:

val l1 = List("a", "b") val l2 = List(1, 2) 

and I would like to generate this:

  List ( List(('a', 1), ('b', 1)), List(('a', 1), ('b', 2)), List(('a', 2), ('b', 1)), List(('a', 2), ('b', 2)) ) 

What is the first list combined with the second to create a list of tuple list? Thought to use foldLeft with sliding (2.2) to get my results, but can't just get the correct result.

The solution should work with any sizes and types, such as List ('a', 'b', 'c') and List ("1", "2")

thanks

+9
scala
source share
2 answers

Harder than I thought! The first step is to calculate the n-Cartesian product l2, which can be done using a combination of List.fill , combinations and permutations (I find it hard to believe that there is no simpler way to do this, but I did not find them):

 def prod[T](lst: List[T], n: Int) = List.fill(n)(lst).flatten.combinations(n).flatMap(_.permutations) 

The value of n determined by the size of the list l1 . In your example, prod(l2, 2) will provide us with List(List(1, 1), List(1, 2), List(2, 1), List(2, 2)) . The rest is just a map and zip application. Together we have

 prod(l2, l1.size).map(l1.zip(_)) 

The output for l1 = List('a', 'b', 'c'), l2 = List("1", "2") :

 List((a,1), (b,1), (c,1)) List((a,1), (b,1), (c,2)) List((a,1), (b,2), (c,1)) List((a,2), (b,1), (c,1)) List((a,1), (b,2), (c,2)) List((a,2), (b,1), (c,2)) List((a,2), (b,2), (c,1)) List((a,2), (b,2), (c,2)) 
+14
source share

The best way is to use for understanding. Much cleaner than the IMO decision :)

 for { i1 <- List('a', 'b', 'c') i2 <- List(1, 2) } yield List(i1, i2) 
0
source share

All Articles