6

生成一组元组的传递闭包的最佳方法是什么?

例子:

  • 输入Set((1, 2), (2, 3), (3, 4), (5, 0))
  • 输出Set((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (5, 0))
4

4 回答 4

7
//one transitive step
def addTransitive[A, B](s: Set[(A, B)]) = {
  s ++ (for ((x1, y1) <- s; (x2, y2) <- s if y1 == x2) yield (x1, y2))
}

//repeat until we don't get a bigger set
def transitiveClosure[A,B](s:Set[(A,B)]):Set[(A,B)] = {
  val t = addTransitive(s)
  if (t.size == s.size) s else transitiveClosure(t)
}

println(transitiveClosure(Set((1,2), (2,3), (3,4))))

这不是一个非常有效的实现,但它很简单。

于 2011-05-11T11:13:41.020 回答
3

在 的帮助下unfold

def unfoldRight[A, B](seed: B)(f: B => Option[(A, B)]): List[A] = f(seed) match {
  case Some((a, b)) => a :: unfoldRight(b)(f)
  case None => Nil
}

def unfoldLeft[A, B](seed: B)(f: B => Option[(B, A)]) = {
  def loop(seed: B)(ls: List[A]): List[A] = f(seed) match {
    case Some((b, a)) => loop(b)(a :: ls)
    case None => ls
  }

  loop(seed)(Nil)
}

它变得相当简单:

def transitiveClosure(input: Set[(Int, Int)]) = {
    val map = input.toMap
    def closure(seed: Int) = unfoldLeft(map get seed) {
        case Some(`seed`) => None
        case Some(n)      => Some(seed -> n -> (map get n))
        case _            => None
    }
    map.keySet flatMap closure
}

另一种写法closure是这样的:

def closure(seed: Int) = unfoldRight(seed) {
    case n if map.get(n) != seed => map get n map (x => seed -> x -> x)
    case _ => None
}

我不确定自己最喜欢哪种方式。我喜欢测试 forSome(seed)以避免循环的优雅,但是,同样的,我也喜欢映射map get n.

两个版本都没有返回seed -> seedfor 循环,因此如果需要,您必须添加它。这里:

    def closure(seed: Int) = unfoldRight(map get seed) {
        case Some(`seed`) => Some(seed -> seed -> None)
        case Some(n)      => Some(seed -> n -> (map get n))
        case _            => None
    }
于 2011-05-11T21:37:05.073 回答
2

将问题建模为有向图,如下所示:

将元组中的数字表示为图中的顶点。然后每个元组 (x, y) 表示从 x 到 y 的有向边。之后,使用Warshall 算法求图的传递闭包。

对于结果图,然后将每个有向边转换为 (x, y) 元组。那是元组集的传递闭包。

于 2011-05-11T10:26:19.247 回答
0

假设您拥有的是 DAG(示例数据中没有循环),您可以使用下面的代码。它期望 DAG 作为从 T 到 List[T] 的映射,您可以从输入中使用

input.groupBy(_._1) mapValues ( _ map (_._2) )

这是传递闭包:

def transitiveClosure[T]( dag: Map[ T, List[T] ] ) = {
  var tc = Map.empty[ T, List[T] ]
  def getItemTC( item:T ): List[T] = tc.get(item) match {
    case None =>
      val itemTC = dag(item) flatMap ( x => x::getItemTC(x) )
      tc += ( item -> itemTC )
      itemTC
    case Some(itemTC) => itemTC
  }
  dag.keys foreach getItemTC
  tc
}

这段代码只计算出每个元素的闭包一次。然而:

  • 如果通过 DAG 的路径足够长(递归不是尾递归),此代码可能会导致堆栈溢出。
  • 对于大图,如果您想要一个不可变的 Map,最好将 tc 制作为可变 Map,然后在最后转换它。
  • 如果您的元素确实像示例中的小整数,则可以通过使用数组而不是映射来显着提高性能,尽管这样做会使某些事情复杂化。

为了消除堆栈溢出问题(对于 DAG),您可以进行拓扑排序、反转它并按顺序处理项目。但另请参阅此页面:

最著名的图传递闭包算法

于 2012-01-31T06:59:18.877 回答