如何生成元组集的传递闭包?
生成一组元组的传递闭包的最佳方法是什么?
示例:
- 输入
Set((1, 2), (2, 3), (3, 4), (5, 0))
- 输出
Set((1, 2), (1 , 3), (1, 4), (2, 3), (2, 4), (3, 4), (5, 0))
What is the best way to generate transitive closure of a set of tuples?
Example:
- Input
Set((1, 2), (2, 3), (3, 4), (5, 0))
- Output
Set((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (5, 0))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这不是一个非常有效的实现,但是很简单。
This is not a very efficient implementation, but it is simple.
在
unfold
的帮助下,它变得相当简单:
编写
closure
的另一种方式是这样的:我自己不确定我最喜欢哪种方式。我喜欢测试
Some(seed)
以避免循环的优雅,但出于同样的原因,我也喜欢映射map get n
结果的优雅。两个版本都不会返回
seed -> Seed
for 循环,因此您必须在需要时添加它。这里:With the help of
unfold
,it becomes rather simple:
Another way of writing
closure
is this:I'm not sure which way I like best, myself. I like the elegance of testing for
Some(seed)
to avoid loops, but, by the same token, I also like the elegance of mapping the result ofmap get n
.Neither version returns
seed -> seed
for loops, so you'll have to add that if needed. Here:将问题建模为有向图,如下所示:
将元组中的数字表示为图中的顶点。
那么每个元组(x,y)代表从x到y的有向边。之后,使用Warshall算法求出图的传递闭包。
对于生成的图,每个有向边都会转换为 (x, y) 元组。这就是元组集合的传递闭包。
Model the problem as a directed graph as follows:
Represent the numbers in the tuples as vertices in a graph.
Then each tuple (x, y) represents a directed edge from x to y. After that, use Warshall's Algorithm to find the transitive closure of the graph.
For the resulting graph, each directed edge is then converted to an (x, y) tuple. That is the transitive closure of the set of tuples.
假设您拥有的是 DAG(示例数据中没有循环),您可以使用下面的代码。它期望 DAG 作为从 T 到 List[T] 的映射,您可以使用
以下传递闭包从输入中获取它:
此代码仅计算每个元素的闭包一次。但是:
为了消除堆栈溢出问题(对于 DAG),您可以进行拓扑排序,反转它,然后按顺序处理项目。但另请参阅此页面:
最著名的图传递闭包算法
Assuming that what you have is a DAG (there are no cycles in your example data), you could use the code below. It expects the DAG as a Map from T to List[T], which you could get from your input using
Here's the transitive closure:
This code figures out the closure for each element just once. However:
To eliminate the stack overflow problem (for DAGs), you could do a topological sort, reverse it, and process the items in order. But see also this page:
best known transitive closure algorithm for graph