I have an array:
["7", "8", "11", "13", "14"]
I want the closest inferior number to 11
if any (i.e., 8
), or if such a number does not exist, then the closest superior number to 11
(i.e., 13
).
So if the array is like [2, 5, 6, 7, 8, 8, 9] and the target number is 4, then closest element is 5. We can solve this by traversing through the given array and keep track of absolute difference of current element with every element. Finally return the element that has minimum absolute difference.
Try the below shortest method for getting the closest value:
n = 40
a = [20, 30, 45, 50, 56, 60, 64, 80]
a.min_by{|x| (n-x).abs}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With