2013-08-26 35 views
-1

我無法弄清楚爲什麼我無法得到正確的偶數長度部分。在紅寶石中查找偶數長度數組的中位數

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,且其第三和第四索引值7和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 ==) 

我已經看到了一個較短的解決方案,但是如果我能理解我想要遵循的邏輯路徑,我是最好奇的,謝謝你一起玩!

解決方案我已經看到:

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

回答

0

數組是零索引。所以如果長度爲4,則需要取指數12的平均值。您當前的企圖將採取指數32的平均值爲4的長度所以,你只需要改變一個小的事情(加爲負):

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

對於偶數Fixnum對象n,這始終是真實的:(n - 1)/2 == (n/2) - 1,這意味着你已經找到了與你找到的類似的方法。這並不令人感到意外,有效地計算中位數的方法有限。

0

這是我對你整個問題的解決方案。你需要使用-1這就是「arr [(arr.length/2)-1]」的原因。你也可以使用2.0而不是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])