找到一个数组的中位数 [英] Find the median of an array

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

问题描述

我写了一些code,它返回一个未排序的奇数数组的中位数,但它不返回偶数数组的中位数。

我知道,为了找到一个偶数数组的中位数,你必须采取数组的中间两个数字,平均他们,这就是中位数。我无法翻译成可用的code。除了这个code的明显冗长,这个问题似乎与第7-8行,我不明白为什么。

我preFER提示来回答,但如果你愿意张贴一些固定的code,我可以接受了。

 高清媒体(阵列)
  分类=的Array.sort
  清单= sorted.length
  如果列表%2!= 0
    (列表+ 1)/ 2.0
  其他
    甚至=((list.to_f + 2)/ 2)+((list.to_f / 2)
    返回(偶/ 2)
  结束
结束


解决方案

我要自己跳在这里解决方案...

  DEF中位数(元)
  中期= ary.length / 2
  分类= ary.sort
  ary.length.odd? ?排序[MID]:0.5 *(排列[MID] +排序[中旬 - 1])
结束

编辑 - ?我已经纳入 .odd 按BroiSatse的建议

I wrote some code that returns the median of an unsorted odd numbered array, but it does not return the median of an even numbered array.

I know that in order to find the median of an even numbered array, you have to take the middle two numbers of the array, average them, and that's the median. I can't translate that into usable code. Aside from the obvious verbosity of this code, the issue seems to be with lines 7-8 and I don't see why.

I prefer hints to answers, but if you rather post some fixed code, I can accept that too.

def media(array)
  sorted = array.sort
  list = sorted.length
  if list %2 != 0
    (list + 1) / 2.0
  else
    even = ((list.to_f + 2) / 2) + ((list.to_f / 2)
    return (even/2)
  end
end

解决方案

I'm going to just jump in with a solution here...

def median(ary)
  mid = ary.length / 2
  sorted = ary.sort
  ary.length.odd? ? sorted[mid] : 0.5 * (sorted[mid] + sorted[mid - 1])
end

Edit - I've incorporated .odd? as per BroiSatse's suggestion.

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

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