I am trying to rearrange/sort a list i.e.
{{1,2},{10,140},{43,10},{1,140},{43,2}}
into
{{1,2},{2,43},{43,10},{10,140},{140,1}}
or any cyclic permutation of it. The numbers don't repeat more than twice. It needs to be rather efficient since I am applying to large lists, in a large sets of lists.
I have a quick code that seems to do the job, but I don't like all those appends.
Myarrangemnt[list_] :=
Module[{x = list, len = Length[list], finalarragment = {First@list},tt},
x = Drop[x, {1}];
While[Length[finalarragment] < len,
tt = First@
Cases[x,
y_ /; Equal[Last@Last@finalarragment, y[[1]]] ||
Equal[Last@Last@finalarragment, y[[2]]]];
If[First[tt] == Last@Last@finalarragment,
finalarragment = Append[finalarragment, tt],
finalarragment = Append[finalarragment, Reverse@tt]
];
x = Drop[x, First@Position[x, tt]];
];
Return[finalarragment];
];
Here is a random test list
test = RandomSample /@ (RandomSample@
Partition[RandomInteger[{1, 1000}, 100], 2, 1, -1])
Is there a more efficient way to achieve this ? Maybe with Reap
and Sow
and/or SortyBy
?