Re: sorting a nested list of 4-tuples
- To: mathgroup at smc.vnet.net
- Subject: [mg120385] Re: sorting a nested list of 4-tuples
- From: Ray Koopman <koopman at sfu.ca>
- Date: Thu, 21 Jul 2011 05:45:44 -0400 (EDT)
- References: <j03o4c$a64$1@smc.vnet.net>
On Jul 19, 4:00 am, Luis Valero <luis.val... at mac.com> wrote: > Dear Sirs, > > I want to sort a list of 4-tuples of real numbers, so that, the second 4-tuple has minimum distance to the first, the third, selected from the rest, ha minimum distance to the second, and so on. > > The distance is the euclidean distance, calculated with the first two elements of each 4-tuple. > > I have defined a function that work: > > orderedList[list_] := Module[{nearest}, > Flatten[ Nest[{ > Append[ #[[1]] , nearest = Flatten @@ Nearest[ Map[ Rule[ #[[{1, 2}]], #] &, #[[2]] ], Last[ #[[1]] ] [[{1, 2}]], 1] ], > Delete[ #[[2]], Position[ #[[2]], nearest ] ] } &, { {list[[1]] }, Delete[ list, 1 ] }, Length[ list ] - 2], 1] ]; > > but I need to improve the temporal efficiency > > Thank you This is faster than the code in my previous post (in which the line 'Do[dd[[i,i]] = ddx,{i,n}];' should be deleted because it was left over from an earlier version and is no longer needed): n = Length[xy = {{0.9238265948180384, 0.8222225655013509}, {0.36916681632329446, 0.352365112953319}, {0.30998090503173714, 0.7924465475420762}, {0.3758287909737646, 0.9537228544636929}, {0.6802940452860295, 0.5941374424537628}, {0.41101146869486416, 0.09869197753233201}, {0.2955842108802197, 0.08604736979206176}, {0.7493387235460567, 0.9271268053705936}, {0.26356623115061834, 0.04310983468962257}, {0.06849589850565166, 0.23097371847465945}}] 10 dd = DistanceMatrix@xy; q = Range@n; NestList[(q = SparseArray[q,Automatic,#] /. SparseArray[_,_,_,x_] :> x[[3]]; q[[Ordering[dd[[#,q]],1][[1]]]])&, 1, n-1] {1,8,5,2,6,7,9,10,3,4}