Generating all possible combinations from a List[List[Int]] in Scala

后端 未结 3 673
暗喜
暗喜 2020-12-16 04:51

Given the following list:

List(List(1,2,3), List(4,5))

I would like to generate all the possible combinations. Using yield, it

3条回答
  •  甜味超标
    2020-12-16 05:48

    Feels like your problem can be described in terms of recursion:

    If you have n lists of int: list1 of size m and list2, ... list n

    • generate the X combinations for list2 to n (so n-1 lists)
    • for each combination, you generate m new ones for each value of list1.
    • the base case is a list of one list of int, you just split all the elements in singleton lists.

    so with List(List(1,2), List(3), List(4, 5)) the result of your recursive call is List(List(3,4),List(3,5)) and for each you add 2 combinations: List(1,3,4), List(2,3,4), List(1,3,5), List(2,3,5).

提交回复
热议问题