Possible Duplicate:
Computing the equivalence classes of the symmetric transitive closure of a relation
I am required to process sets consisting of 2-element subsets of integers by combining those subsets whose intersection is nonempty.
For example, given
X = {{1, 2}, {3, 4}, {7, 4}, {2, 5}}
my routine merge
will output
merge[X] = {{3, 4, 7}, {1, 2, 5}}
.
As all List
elements are considered as sets, duplicate entries and list order are to be ignored.
In fact I have implemented such an algorithm in Mathematica, however I suspect it is horribly inefficient and am looking for any reasonable way to improve its performance.
My implementation uses FixedPoint and is broken into two parts :
merge0[x_] := Block[{x0 = x},
Do[
If[i != j && Intersection[x[[i]], x[[j]]] != {},
x0 = Join[Delete[x, {{i}, {j}}], {Union@Flatten[Join[x[[i]], x[[j]]]]}];
Break[]],
{i, Length[x]}, {j, i}]; x0]
merge[x_] := FixedPoint[merge0, x]
Thanks and regards,
Daniel
Comments
Post a Comment