Get the closest value to number
Pyth, 6 bytes
haDQSE
Input in the following form on STDIN:
num
array
Explanation:
haDQSE
Implicit: Q = eval(input()) (num)
E Evaluate input (array)
S Sort (smaller values to the front)
aDQ Sort by absolute difference with Q.
h Take the first element of the sorted list, the min.
Print implicitly.
Ruby, 34 bytes
->n,a{a.sort.min_by{|x|(n-x).abs}}
a.sort min_by tiebreaks by position in array, so put smaller numbers 1st
.min_by{|x| select the element which returns the smallest val for predicate...
(n-x).abs} (absolute) difference between input num and element
Mathematica, 12 bytes
Min@*Nearest
Built-ins FTW! Buettner's explanation: "Mathematica has a built-in Nearest
for this, but it returns a list of all tied numbers. Hence, we need to compose it with Min
to break the tie."