Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...