找到红宝石中偶数长度数组的中位数 [英] Finding median for even length array in ruby

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

问题描述

我无法弄清楚为什么我的偶数长度部分不正确。

I cannot figure out why I cannot get the even length portion correct.

def median(array)
  array.sort!
  if array.length % 2 == 0                                            #if amount of array members is even
    (array[(array.length/2) + 1] + array[array.length/2]) / 2.to_f    #return average of the 2 middle array members
  else                                                                #if amount of array members is odd
    array[array.length/2.ceil]                                        #return middle number
  end   
end

我的尝试是例如一个长度为6的数组,其第3和第4个索引值为7和9.

My attempt is for example, an array whose length is 6, and whose 3rd and 4th index value are 7 and 9.

array[6/3+1] + array [6/3]
(array[4] + array[3]) /2
9 + 7 / 2

我收到此错误

Error!
median returns the correct median of an even-length array
expected: 5.5 got: 6.0 (compared using ==)

我见过一个较短的解决方案,但是如果我能理解我想要遵循的逻辑路径,那就太好奇了,谢谢你们一起玩吧!

I have seen a shorter solution, but am most curious if I can make sense of the logic path I am trying to follow, thanks for playing along!

解决方案我见过:

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


推荐答案

数组是零索引的。因此,如果长度为4,则需要取平均指数 1 2 。您当前的尝试将平均指数 3 2 的长度为4.所以你只需要更改一个小东西(加上减去):

Arrays are zero-indexed. So if the length was 4, you need to be taking average of indices 1 and 2. Your current attempt would take average of indices 3 and 2 for a length of 4. So you just need to change one small thing (plus into minus):

(array[(array.length/2) - 1] + array[array.length/2]) / 2.to_f

对于偶数编号的Fixnum n ,这总是如此:(n - 1)/ 2 ==(n / 2) - 1 ,这意味着你已经找到了与你找到的方法类似的方法。这并不太令人惊讶,有效地计算中位数的方法有限。

For an even numbered Fixnum n, this is always true: ( n - 1 ) / 2 == ( n / 2 ) - 1, which means you have figured out a similar approach to the one you found. This is not too surprising, there are a limited number of ways to calculate medians efficiently.

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

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