【问题标题】:Generate combinations using items from different sets in Scala在 Scala 中使用来自不同集合的项目生成组合
【发布时间】:2016-07-07 15:04:15
【问题描述】:

假设我有一个集合列表,例如

scala> val a = List(Set(1, 2, 3), Set(4, 5), Set(6, 7, 8, 9))

我想生成一个包含所有可能项目组合的列表,每个组合对应于列表中的每个集合(以功能方式)。例如,

List(Set(1, 4, 6), Set(1, 4, 7), ...)

【问题讨论】:

标签: scala functional-programming combinations


【解决方案1】:
input.foldLeft(List[Set[Int]](Set.empty)) {
  case (acc, set) =>
    for {
      accSet <- acc
      n <- set
    } yield accSet + n
}

【讨论】:

    【解决方案2】:

    只是在迈克尔的回答中添加一点概括,以涵盖“项目”的要求:

      def setCombos[A](xsa: List[Set[A]]): List[Set[A]] =
        xsa.foldLeft(List[Set[A]](Set.empty)) {
          (acc, set) =>
            for {
              accSet <- acc
              n <- set
            } yield accSet + n
        }
    

    【讨论】:

      【解决方案3】:
      object Demo extends App {
        def cartesian[T](x: List[List[T]]): List[List[T]] = {
          def partialCartesian(x: List[T], y: List[List[T]]): List[List[T]] =
            for {
              head <- x
              tail <- y
            } yield head +: tail
      
          x match {
            case head :: Nil => head.map(List(_))
            case head :: tail => partialCartesian(head, cartesian(tail))
          }
        }
      
        val a = List(List(1, 2, 3), List(4, 5), List(6, 7, 8, 9))
        cartesian(a).foreach(println)
      }
      
      >> List(1, 4, 6)
      >> List(1, 4, 7)
      >> List(1, 4, 8)
      >> List(1, 4, 9)
      >> List(1, 5, 6)
      >> List(1, 5, 7)
      >> List(1, 5, 8)
      >> List(1, 5, 9)
      >> List(2, 4, 6)
      >> List(2, 4, 7)
      >> List(2, 4, 8)
      >> List(2, 4, 9)
      >> List(2, 5, 6)
      >> List(2, 5, 7)
      >> List(2, 5, 8)
      >> List(2, 5, 9)
      >> List(3, 4, 6)
      >> List(3, 4, 7)
      >> List(3, 4, 8)
      >> List(3, 4, 9)
      >> List(3, 5, 6)
      >> List(3, 5, 7)
      >> List(3, 5, 8)
      >> List(3, 5, 9)
      

      我使用 'List' 而不是 'Set' - 用于最短代码。 附:对不起我的英语。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-21
        • 1970-01-01
        • 2012-01-11
        • 2012-05-15
        • 2012-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多