scala - How to generate transitive closure of set of tuples? -
what best way generate transitive closure of 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))
//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 don't 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))))
this not efficient implementation, simple.
Comments
Post a Comment