Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Round number down to nearest number based on arbitrary list of numbers

Say I have an array of integers:

arr = [0,5,7,8,11,16]

and I have another integer:

n = 6

I need a function that rounds down to the nearest number from the array:

foo(n) #=> 5

As you can see, the numbers do not have a fixed pattern. What's an elegant way to do this?

Thanks

like image 486
user94154 Avatar asked Jul 01 '10 18:07

user94154


2 Answers

Use select followed by max:

arr = [0,5,7,8,11,16]
puts arr.select{|item| item < 6}.max

Result:

5

This runs in linear time and doesn't require that the array is sorted.

like image 67
Mark Byers Avatar answered Oct 21 '22 06:10

Mark Byers


If you are using relatively small arrays (and so not overly worried about efficiency), then this should work fine:

def down_to_array num, arr
  arr.select{|y| y < num}.sort_by{|z| num-z }.first
end

E.g:

myarr = [0,5,7,8,11,16]
puts down_to_array 6.5, myarr #=> 5
like image 28
unignorant Avatar answered Oct 21 '22 07:10

unignorant