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 + array) /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
Arrays are zero-indexed. So if the length was 4, you need to be taking average of indices
2. Your current attempt would take average of indices
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.
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])