sort array of floating point numbers in tcl

64 views Asked by At

I just learned about tcl. I'm sorting an array of integers but I get the error. I still don't know how to solve this problem.

puts [lsort [list 22.678 11.456 7.6 3.521 8.9 4.987 9.245 10.7765]]

The result is:

10.7765 11.456 22.678 3.521 4.987 7.6 8.900 9.245

but I want them sorted ascending:

3.521 4.987 7.6 8.900 9.245 10.7765 11.456 22.678
1

There are 1 answers

1
Vietnamese On

In Tcl, the lsort command is used to sort lists. By default, lsort treats each element as a string, which is why you're seeing the results in lexicographic order rather than numerical order. To sort the numbers numerically, you need to use the -real or -integer option with lsort, depending on whether you're dealing with real numbers or integers.

However, there's also another issue in your list: the use of commas within the numbers. Tcl will interpret these as part of the string, and not as a thousands separator. To sort the numbers correctly, you should remove the commas.

Here is how you can sort the list numerically after removing the commas:

set numbers [list 22678 11456 7.6 3521 8900 4987 9245 10776]
puts [lsort -real $numbers]

If you want to keep the commas as thousands separators for display purposes, you could remove them before sorting and then add them back after sorting. Here's an example of how you could do that:

# Original list with commas
set numbers_with_commas [list 22,678 11,456 7.6 3,521 8,900 4,987 9,245 10,776]

# Remove commas for sorting
set numbers [lmap num $numbers_with_commas {regsub -all {,} $num ""}]

# Sort numerically
set sorted_numbers [lsort -real $numbers]

# Add commas back for display
set sorted_numbers_with_commas [lmap num $sorted_numbers {
    # Here you could format the number to have commas, but Tcl doesn't have a built-in way to do this.
    # You would need to write a function to add the commas back in the correct places if needed.
    # For simplicity, this example just returns the number without commas.
    return $num
}]

# Output the result
puts "Sorted numbers: $sorted_numbers_with_commas"

Please note that Tcl doesn't have a built-in way to format numbers with commas as thousands separators, so if you need that functionality, you would have to implement it yourself or use a package that provides such functionalit