henix / blog

some notes
0 stars 0 forks source link

笛卡尔积(Cartesian product) #11

Closed henix closed 10 years ago

henix commented 11 years ago

有若干集合,从每个集合中任选一元素,求所有的组合。

也就是把原来外层是 and 、内层是 or 的表达式改写成外层是 or 、内层是 and 的表达式。应用来源是 mongodb 的 1.6 版本不支持用 $and 写查询...

(1 or 2 or 3) and (4 or 5 or 6)

笛卡尔积:

(1,4) or (2,4) or (3,4) or (1,5) or (2,5) or (3,5) or (1,6) or (2,6) or (3,6)
henix commented 11 years ago

Scala 版:Nil 的结果是 List(Nil) 而不是 Nil

  def selectEach[A](list: List[List[A]]): List[List[A]] = list match {
    case Nil => List(Nil)
    case head::others => selectEach(others).flatMap((c) => head.map((e) => e::c))
  }
henix commented 10 years ago

Python: http://docs.python.org/2/library/itertools.html#itertools.product