ruby - Find the median of an array -


i wrote code returns median of unsorted odd numbered array, not return median of numbered array.

i know in order find median of numbered array, have take middle 2 numbers of array, average them, , that's median. can't translate usable code. aside obvious verbosity of code, issue seems lines 7-8 , don't see why.

i prefer hints answers, if rather post fixed code, can accept too.

def media(array)   sorted = array.sort   list = sorted.length   if list %2 != 0     (list + 1) / 2.0   else     = ((list.to_f + 2) / 2) + ((list.to_f / 2)     return (even/2)   end end 

i'm going jump in solution here...

def median(ary)   mid = ary.length / 2   sorted = ary.sort   ary.length.odd? ? sorted[mid] : 0.5 * (sorted[mid] + sorted[mid - 1]) end 

edit - i've incorporated .odd? per broisatse's suggestion.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -