Cartesian product of two lists

后端 未结 3 844
一整个雨季
一整个雨季 2020-11-29 06:34

Given a map where a digit is associated to several characters

scala> val conversion = Map(\"0\" -> List(\"A\", \"B\"), \"1\" -> List(\"C\", \"D\"))
         


        
相关标签:
3条回答
  • 2020-11-29 07:11

    The following suggestion is not using a for-comprehension. But I don't think it's a good idea after all, because as you noticed you'd be tied to a certain length of your cartesian product.

    scala> def cartesianProduct[T](xss: List[List[T]]): List[List[T]] = xss match {
         |   case Nil => List(Nil)
         |   case h :: t => for(xh <- h; xt <- cartesianProduct(t)) yield xh :: xt
         | }
    cartesianProduct: [T](xss: List[List[T]])List[List[T]]
    
    scala> val conversion = Map('0' -> List("A", "B"), '1' -> List("C", "D"))
    conversion: scala.collection.immutable.Map[Char,List[java.lang.String]] = Map(0 -> List(A, B), 1 -> List(C, D))
    
    scala> cartesianProduct("01".map(conversion).toList)
    res9: List[List[java.lang.String]] = List(List(A, C), List(A, D), List(B, C), List(B, D))
    

    Why not tail-recursive?

    Note that above recursive function is not tail-recursive. This isn't a problem, as xss will be short unless you have a lot of singleton lists in xss. This is the case, because the size of the result grows exponentially with the number of non-singleton elements of xss.

    0 讨论(0)
  • 2020-11-29 07:19

    I could come up with this:

    val conversion = Map('0' -> Seq("A", "B"), '1' -> Seq("C", "D"))
    
    def permut(str: Seq[Char]): Seq[String] = str match {
      case Seq()  => Seq.empty
      case Seq(c) => conversion(c)
      case Seq(head, tail @ _*) =>
        val t = permut(tail)
        conversion(head).flatMap(pre => t.map(pre + _))
    }
    
    permut("011")
    
    0 讨论(0)
  • 2020-11-29 07:20

    I just did that as follows and it works

        def cross(a:IndexedSeq[Tree], b:IndexedSeq[Tree]) = {
            a.map (p => b.map( o => (p,o))).flatten
        }
    

    Don't see the $Tree type that am dealing it works for arbitrary collections too..

    0 讨论(0)
提交回复
热议问题