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)?
Prepend
andAppend
based solution can indeed become comparatively slow... $\endgroup$ – Yves Klett Jan 8 '13 at 9:00f[x_List,pos_Integer]:=x[[pos]]
. $\endgroup$ – image_doctor Jan 8 '13 at 11:08FindShortestTour
? $\endgroup$ – Rojo Jan 8 '13 at 14:10