Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

How can I sort the following list:

list={{1498, 1495}, {1498, 1733}, {1553, 1552}, {1552, 1495}, {1733,1776}, {1776, 1553}};

such that the next group contains one element of the first. The result would be:

{{1498, 1495}, {1552, 1495}, {1553, 1552}, {1776, 1553}, {1733,1776}, {1498, 1733}}

Sort[list,SameQ] 

does not work completely as the results are still incorrectly sorted.

{{1498, 1495}, {1498, 1733}, {1553, 1552}, {1552, 1495}, {1733,1776}, {1776, 1553}} 

It does not matter if the elements are in increasing order. An equally acceptable result would be

{{1498, 1495}, {1498, 1733}, {1733, 1776}, {1776, 1553},{1553, 1552}, {1552, 1495}}
share|improve this question

closed as unclear what you're asking by Mr.Wizard Feb 7 at 15:28

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

    
Sorting with an equality test (SameQ) doesn't make sense. The test you used should be a ranking test (like OrderedQ, or Less) –  Sjoerd C. de Vries Feb 7 at 15:15
    
This question does not seem to be well specified, so I have closed to to prevent wasted efforts. Would you please describe the algorithm that you wish to implement, or the specific characteristics of the result that you wish to obtain? –  Mr.Wizard Feb 7 at 15:29

2 Answers 2

I am not sure if you still want the list to be sorted by increasing order at all. If not, here is a solution:

f[{a___, i_, j_, b___}] /; 
  i[[1]] =!= j[[1]] && i[[1]] =!= j[[2]] && i[[2]] =!= j[[1]] && 
   i[[2]] =!= j[[2]] := f[{a, i, b, j}]

list = {{1498, 1495}, {1498, 1733}, {1553, 1552}, {1552, 1495}, {1733,
     1776}, {1776, 1553}};

f[list][[1]]

{{1498, 1495}, {1498, 1733}, {1733, 1776}, {1776, 1553}, {1553, 1552}, {1552, 1495}}

share|improve this answer
l = {{1498, 1495}, {1552, 1495}, {1553, 1552}, {1776, 1553}, {1733, 1776}, {1498, 1733}};
p = List @@@ First@FindHamiltonianCycle[Graph[UndirectedEdge @@@ l]];
p /. {x_, y_} :> {y, x} /; ! MemberQ[l, {x, y}]
(*
 {{1498, 1495}, {1552, 1495}, {1553, 1552}, {1776, 1553}, {1733, 1776}, {1498, 1733}}
*)
share|improve this answer
    
I think an Eulerian cycle is what is desired here (we don't want to drop any edges). –  Rahul Feb 7 at 16:20
    
@RahulNarain Thanks! I was waiting for an edit to clarify the question to understand what kind of cycle we should seek. –  belisarius Feb 7 at 16:43

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