Version 2 of Closest Hit - Choosing closest matches to a target value

Updated 2017-06-24 16:41:24 by WJG

WJG (24/06/17) Given a list of integers which ones are closest to some target value?

#---------------
# determine which items from a list of integers are closest to a target value
#---------------
# Args:
#   arrows   list of integer
#   target   target value
# Returns:
#   indices of values in the list which are closest to the target value
#
proc closest_hit { arrows target} {

        set last 0
        set res ""
        
        for { set i 0 }  { $i < [llength $arrows] } { incr i } {
                set diff [expr abs($target - [lindex $arrows $i])]
                if { $diff == 0 } { lappend res $i }
                if { $diff < $last } { set res $i }
                set last $diff 
        }
        
        return $res
} 


puts [closest_hit "5 6 10 20 30 10" 10]