Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to sort a coordinate list according to the x coordinate

Status
Not open for further replies.

tcltkmail

Programmer
Feb 14, 2002
3
0
0
DE
hi,

I have a coordinate list like this {x1 y1 x2 y2 x3 y3...xn yn}. How to sort this list according to the x coordinate?

Thank you very much.

Joye
 
The best way I know of is to make your list into a list of lists: {{x1 y1} {x2 y2} ...} Then use "lsort" on index 0. Bob Rashkin
rrashkin@csc.com
 
I agree that if you have control over the format of the list, it's going to be a lot easier to sort them in the manner you want using Bong's tip. Unfortunately, sometimes you don't have the luxury of designing the data format.

Equally unfortunate, there's no obvious way of doing this kind of sorting in Tcl. The best way I've been able to figure out transforms the list into an array and back for speed and simplicity. Here's what I did:

[tt]% [ignore]for {set i 0} {$i < 10} {incr i} {
lappend coords [expr {2000.0*rand()-1000}] [expr {2000.0*rand()-1000}]
}[/ignore]

% puts $coords
893.827048081 551.197095565 -30.414836961 817.835195837 -643.863575367 584.888803579 226.12175775 428.382511916 -175.122230861 720.665920396 232.124090768 -690.406454583 338.717825403 830.491545531 71.4057428164 116.3195144 982.078513122 -206.42995518 531.743289685 -990.530268285
% array set tempcoords $coords
% [ignore]foreach x [lsort -real [array names tempcoords]] {
lappend newcoords $x $tempcoords($x)
}[/ignore]

% puts $newcoords
-643.863575367 584.888803579 -175.122230861 720.665920396 -30.414836961 817.835195837 71.4057428164 116.3195144 226.12175775 428.382511916 232.124090768 -690.406454583 338.717825403 830.491545531 531.743289685 -990.530268285 893.827048081 551.197095565 982.078513122 -206.42995518[/tt]

The summary:
[ol][li]Use array set to create an array from the coordinate list.[/li]
[li]Use array names to retrieve a list of just the keys (the x coordinates, in this case).[/li]
[li]Sort the keys (x coordinates) using lsort -real.[/li]
[li]Loop through the sorted keys and use lappend to append the key and its corresponding value to the new, sorted list.[/li][/ol] - Ken Jones, President
Avia Training and Consulting
866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top