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

ⅰ亾dé卋堺 提交于 2019-12-22 04:11:46

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/3160502/ruby-round-number-down-to-nearest-number-based-on-arbitrary-list-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!