Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...