3
$\begingroup$

I have a nested list with n row and 2 column, its values are numbers, Can I change the order of elements according to the second value?? so every element have in its second value the same value in the first of the next element Example:

y = {{1,4}, {2,3}, {4,2}, {3,1}}

I want to start from the element contains 1, then it contains 4, I want to put the element contains 4 as its first value after it so it would be {4,2}, and the next must be {2,3}, and so on...

output = {{1,4}, {4,2}, {2,3}, {3,1}}

the elements always contains two values only is there any function can do this or I must do this manually???? thank you

$\endgroup$
0

1 Answer 1

7
$\begingroup$
y = {{1, 4}, {2, 3}, {4, 2}, {3, 1}};

If the input list is pairs of integers, you can use FindHamiltonianPath:

y[[FindHamiltonianPath[y]]]
{{1, 4}, {4, 2}, {2, 3}, {3, 1}}

In general, you can construct a list of UndirectedEdges from the input list and use a combination of FindHamiltonianPath and Partition:

y2 = N @ y
{{1., 4.}, {2., 3.}, {4., 2.}, {3., 1.}}
Partition[FindHamiltonianPath[UndirectedEdge @@@ y2], 2, 1]
{{1., 4.}, {4., 2.}, {2., 3.}}
$\endgroup$
1
  • 2
    $\begingroup$ thank you very much, that's exactly what I want, because this is the solution for the optimal path of TSP problem and I want to construct the hamilton path from variables in solution $\endgroup$
    – RHH
    Jan 30 at 23:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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