即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

红宝石中偶长数组的中位数

栈溢出 sage 11℃ 0评论
本文目录
[隐藏]

1.原始问题:Finding median for even length array in ruby

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

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

I am receiving this error

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!

Solution I have seen:

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

2.被采纳答案

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

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.

3.其他高票答案

3.1.第1个答案

Here is my solution to your whole problem. you need use to -1 that’s the reason “arr[(arr.length/2)-1]”. Also you can use 2.0 instead of 2.to_f.

#Write a method that finds the median of a given array of integers. If the array has an odd number of integers,
# return the middle item from the sorted array. If the array has an even number of integers, 
# return the average of the middle two items from the sorted array.


def find_median(arr)
arr.sort!
  if arr.length.even?
       return (arr[arr.length/2] + arr[(arr.length/2)-1])/2.0
  else #else odd
       return arr[arr.length/2.0]
  end
end

puts find_median([2,3,4,9,7,8])

转载请注明:CodingBlog » 红宝石中偶长数组的中位数

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情