4 ms·
The larger version can be done without the expr command in the if statement: proc nearestneighbours {numlist number} { # For a given number, find the ne
by pmarin 17y ago
The larger version can be done without the expr command in the if statement:
proc nearestneighbours {numlist number} {
# For a given number, find the nearest lower and higher numbers in
# a given (ordered) list of numbers.
set left 0
set right 1000000000
foreach i $numlist {
if { $i < $number && $i > $left} {set left $i} elseif {
$i > $number && $i < $right} {set right $i}
} ;# end foreach
set nearest [list $left $right]
return $nearest
} ;# end proc findnearest
proc main {} {
# Demo when called directly.
set mylist [list "58163" "62140" "66139" "70280" "74371" "78525" "82426" "86584" "90650" "94749"]
set number 67000
set highlow [nearestneighbours $mylist $number]
puts "Lower: [lindex $highlow 0]"
puts "Higher: [lindex $highlow 1]"
} ;# end proc main
main