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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…