在 Ruby 中查找数组中的最高值、最低值、总计、平均值和中位数
我正在用 Ruby 创建一个箱线图生成器,我需要计算一些东西。
假设我有这个数组:
arr = [1, 5, 7, 2, 53, 65, 24]
如何从上面的数组中找到最小值 (1)、最大值 (65)、总计 (157)、平均值 (22.43) 和中值 (7)?
谢谢
I am creating a boxplot generator in Ruby, and I need to calculate some things.
Let's say I have this array:
arr = [1, 5, 7, 2, 53, 65, 24]
How can I find the lowest value (1), highest value (65), total (157), average (22.43) and median (7) from the above array?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
找到最小值、最大值、总和和平均值很简单,可以在线性时间内轻松完成,如上面 sepp2k 的答案所示。
找到中位数并不那么简单,简单的实现(排序,然后取出中间元素)在 O(nlogn) 时间内运行。
然而,有些算法可以在线性时间内找到中位数(例如 5 中位数算法)。其他方法甚至适用于任何类型的顺序统计(例如,您想找到第五小的元素)。这些的问题是你必须自己实现它们,我知道没有 Ruby 实现。
O(nlogn) 已经相当快了,所以如果您不打算处理大型数据集(并且如果您无论如何都需要对数据进行排序),那么您就可以接受。
Finding the minimum, maximum, sum and average are trivial and can be done easily in linear time as shown by sepp2k's answer above.
Finding the median is less trivial and the naive implementation (sorting, and then taking the middle element) runs in O(nlogn) time.
There are, however, algorithms that find the median in linear time (such as the median-of-5 algorithm). Others work even for any kind of order statistic (say, you want to find the 5th-smallest element). The problem with those is that you would have to implement them yourself, I know of no Ruby implementation.
O(nlogn) is quite fast already, so if you're not planning on working on huge datasets (and if you will need to sort your data anyway), you'll be fine with that.