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

后端 未结 3 668
暗喜
暗喜 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:37

    Ezekiel has exactly what I was looking for. This is just a minor tweak of it to make it generic.

      def generateCombinations[T](x: List[List[T]]): List[List[T]] = {
        x match {
          case Nil => List(Nil)
          case h :: _ => h.flatMap(i => generateCombinations(x.tail).map(i :: _))
        }
      }
    

提交回复
热议问题