4
$\begingroup$

Does anyone know how to obtain 'list2' from 'list1'? ... ... because I got confused. The algorithm will be used for very large lists.

list1 = {{1, 35, 3}, {1, 896, 1}, {2, 3, 999}, {1, 212, 5}, {1, 243, 1}, {3, 2, 88}, {1, 903, 3}, {35, 1, 9}, {1, 914, 1}, {1, 925, 2}, {896, 1, -6}};

list2={{{1, 35, 3}, {35, 1, 9}}, {{1, 896, 1}, {896, 1, -6}}, {{2, 3, 999}, {3, 2, 88}}, {1, 212,5}, {1, 243, 1}, {1, 903, 3}, {1, 914, 1}, {1, 925, 2}};

Of course, the order doesn't matter. The most important thing is that elements #1[[1]] == #2[[2]] || # 1[[2]] == #2[[1]] are in one sublist.

$\endgroup$
1
  • 3
    $\begingroup$ Gather[list1, #1[[1]] == #2[[2]] && #1[[2]] == #2[[1]] &] /. {x_} :> x $\endgroup$
    – ciao
    Sep 8, 2020 at 19:42

1 Answer 1

5
$\begingroup$
Gather[list1, #[[;;2]] == Reverse @  #2[[;;2]] &] /. {x_} :> x
{{{1, 35, 3}, {35, 1, 9}}, 
{{1, 896, 1}, {896, 1, -6}}, 
{{2, 3,  999}, {3, 2, 88}}, 
{1, 212, 5}, {1, 243, 1}, {1, 903, 3}, {1, 914, 1}, {1, 925, 2}}

If input list is a list of triples, you can also use Most[#] in place of #[[;; 2]] &.

We can also construct a graph on list1 using RelationGraph and find its ConnectedComponents to get the same groupings:

relation = #[[;; 2]] == Reverse @ #2[[;; 2]] &;

ConnectedComponents @ RelationGraph[relation, list1] /. {x_} :> x 
{{{2, 3, 999}, {3, 2, 88}},
 {{1, 896, 1}, {896, 1, -6}}, 
 {{1, 35,  3}, {35, 1, 9}}, 
 {1, 925, 2}, {1, 914, 1}, {1, 903, 3}, {1, 243, 1}, {1, 212, 5}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.