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

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -