Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get closest value of a number from array

Tags:

ruby

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).

like image 201
Chetan Barawkar Avatar asked Jan 20 '16 09:01

Chetan Barawkar


People also ask

How do I find the closest number in an array in C?

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.


1 Answers

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}
like image 87
Vishal Avatar answered Oct 06 '22 02:10

Vishal