计算Ruby中的中位数 [英] Calculating Median in Ruby

查看:98
本文介绍了计算Ruby中的中位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Ruby计算数字数组的中位数?

How do I calculate the median of an array of numbers using Ruby?

我是一个初学者,在学习的过程中,我试图坚持已经讲授的内容.因此,我发现的其他问题超出了我的范围.

I am a beginner and within the progress of my learning I am trying to stick to what has already been taught. Thus the other questions that I've found are beyond my scope.

这是我的笔记和尝试:

  1. 以升序对数组进行排序.
  2. 弄清楚它是奇数还是偶数长度.
  3. 如果为奇数,则将排序后的数组长度+1分为两半.那 是中位数的指数.返回此值.
  4. 如果是偶数,请找到已排序数组的中间两个数字并将它们除以1/2. 返回此值.
  5. 找到中间两个数字:
  6. 将排序后的数组长度分成两半.这是索引pt.第一个中间数字.
  7. 将排序后的数组长度除以2.这是索引pt.的 第二个中间数字.
  8. 取这两个中间数字的平均值.

  1. sort the array in ascending order.
  2. figure out if it is odd or even in length.
  3. if odd, divide the sorted array length +1 in half. That is the index of the median. Return this value.
  4. if even, find the middle two numbers of the sorted array and divide them in 1/2. Return this value.
  5. Finding the middle two numbers:
  6. divide the sorted array length in half. This is index pt. first middle number.
  7. divide sorted array length + 2 in half. This is the index pt. of the second middle number.
  8. take average of these two middle numbers.

def median(array)
  ascend = array.sort
  if ascend % 2 != 0
    (ascend.length + 1) / 2.0
  else
    ((ascend.length/2.0) + ((ascend.length + 2)/2.0) / 2.0)
  end
end

推荐答案

这是一个既适用于偶数长度也适用于奇数长度数组且不会更改数组的解决方案:

Here is a solution that works on both even and odd length array and won't alter the array:

def median(array)
  sorted = array.sort
  len = sorted.length
  (sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0
end

这篇关于计算Ruby中的中位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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