# How to group lists that own one common element?

I have produced a list of sub-lists by the following:

pairs = Select[
Sort[{2 #1*#2 + #2^2, #1^2 - #2^2} & @@@
Flatten[Tuples /@
DeleteCases[{{#},
Table[If[GCD[#, i] == 1 && Mod[# - i, 3] != 0, i,
0], {i, # - 1}]} & /@ Range[100], 0, Infinity], 1]],
Plus @@ # < 120000 &];


In this list, every sub-list only has two elements. Now what I want to do is to group the lists in pairs that share one common element. For example, if pairs={{1,2},{3,4},{2,5},{2,6},{5,4},{9,7}}, I want to get the result like this:

{{{1,2},{2,5},{2,6}},{{2,5},{5,4}},{{3,4},{5,4}},{{9,7}}}


That is, find all the lists that have a common element, and group them. Some sub-lists may be grouped twice like {2,5},{5,4}, while some are alone like {9,7}.

I know this can be achieved easily by using the loop Forand While, but I want to get a better and neater code to do this. I've tried GatherBy[list,f], but I don't know how to write the function f. I'd appreciate it if any one could provide some ways.

-

Your sample output seems inconsistent - either you list all elements, including those that are only present in just one pair, or you should not have things like {{9,7}}. Assuming the first scenario, here is a possibility:

DeleteDuplicates[Reap[Sow[#, #] & /@ pairs][[2]]]

(*
{
{{1,2}},
{{1,2},{2,5},{2,6}},
{{3,4}},
{{3,4},{5,4}},
{{2,5},{5,4}},
{{2,6}},
{{9,7}}
}
*)


You can filter out the cases with just one pair by applying Select[#,Length[#]>1&]& to the above result.

-
Thanks very much! It is what I want. In fact, I don't need to get those sub-lists like {9,7}. – Z-Y.L Jul 17 '13 at 12:11
@Z-Y.L Perhaps you want: Cases[Reap[Sow[#, #] & /@ pairs][[2]], {_, __}] – Mr.Wizard Jul 17 '13 at 12:13
Gather[{{1, 2}, {3, 4}, {2, 5}, {2, 6}, {5, 4}, {9, 7}},  Intersection[#1, #2] =!= {} &]


{{{1, 2}, {2, 5}, {2, 6}}, {{3, 4}, {5, 4}}, {{9, 7}}}

But, as Leonid indicates, there is an inconsistency in your definition as the intersection operation is not transitive.

-
Thank you! Gather is more general and flexible than GatherBy. – Z-Y.L Jul 17 '13 at 12:21