红宝石:回合数下降到最近的一些基于号码的任意名单 [英] Ruby: Round number down to nearest number based on arbitrary list of numbers

查看:88
本文介绍了红宝石:回合数下降到最近的一些基于号码的任意名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个整数数组:

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

和我有另一个整数:

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?

感谢

推荐答案

使用<一个href=\"http://ruby-doc.org/core/classes/Enumerable.html#M003125\"><$c$c>select其次是<一个href=\"http://ruby-doc.org/core/classes/Enumerable.html#M003134\"><$c$c>max:

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

结果:

5

这个运行在线性时间,并且不要求该数组排序

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

这篇关于红宝石:回合数下降到最近的一些基于号码的任意名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆