生成一组元组的传递闭包的最佳方法是什么?
例子:
- 输入
Set((1, 2), (2, 3), (3, 4), (5, 0))
- 输出
Set((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (5, 0))
生成一组元组的传递闭包的最佳方法是什么?
例子:
Set((1, 2), (2, 3), (3, 4), (5, 0))
Set((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (5, 0))
//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))))
这不是一个非常有效的实现,但它很简单。
在 的帮助下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 -> seed
for 循环,因此如果需要,您必须添加它。这里:
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
}
将问题建模为有向图,如下所示:
将元组中的数字表示为图中的顶点。然后每个元组 (x, y) 表示从 x 到 y 的有向边。之后,使用Warshall 算法求图的传递闭包。
对于结果图,然后将每个有向边转换为 (x, y) 元组。那是元组集的传递闭包。
假设您拥有的是 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),您可以进行拓扑排序、反转它并按顺序处理项目。但另请参阅此页面: