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

Updated 2017-06-24 16:40:30 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])]
                puts "diff = $diff"
                if { $diff == 0 } { lappend res $i }
                if { $diff < $last } { 
                        puts "$last $diff"
                        set res $i
                        }
                        set last $diff 
        }
        
        return $res
} 


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