I have a list of 2D points (a table, imagine the data of a parametric plot shuffled)
I would like to join the points with a line that starts from one of them and always goes to the closest one.
I tried therefore to sort the points doing the following:
- take out the first element,
- search the closest in the remaining list
- bring it to the front
- recurse
so that I can then use ListLinePlot
As a first step I tried to do it in 1D (yes, in this case a simple sorting is sufficient, but not in the 2D case)
However,I have a problem, because I do not know how to specify that a variable IS a list.
Concretely
BringToFront =
Function[{list, pos}, Prepend[list[[pos]], Drop[list, {pos}]]]
BringClosestToFront =
Fuction[{list, val},
BringToFront[list, Nearest[list ->Automatic, val]]]
Follow[{}] = {};
Follow[list] =
Prepend[list[[1]],
Follow[BringClosestToFront[Drop[list, 1], list[[1]]]]]
And the BringClosestToFront is not accepted, with a
Part::partd: Part specification list[[1]] is longer than depth of object. >>
I am also worried of the speed of this recursive solution. Do you thing there may be a way to specify it in a more procedural way (i.e. implement insertion-sort)?
![[greedy.png]](../../images/db7f2cd60b42863ca04aa70b350b4959.webp)




PrependandAppendbased solution can indeed become comparatively slow... – Yves Klett Jan 08 '13 at 09:00f[x_List,pos_Integer]:=x[[pos]]. – image_doctor Jan 08 '13 at 11:08FindShortestTour? – Rojo Jan 08 '13 at 14:10