ruby - Calculate Median in An Array - Can someone tell me what is going on in this line of code? -


this solution calculating median value in array. first 3 lines, duh ;), third line magic happening. can explain how 'sorted' variable using , why it's next brackets, , why other variable 'len' enclosed in parentheses , brackets? it's sorted of sudden being used array? thanks!

  def median(array)     sorted = array.sort     len = sorted.length     return ((sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0).to_f   end    puts median([3,2,3,8,91])   puts median([2,8,3,11,-5])   puts median([4,3,8,11]) 

consider this:

[1,2,2,3,4] , [1,2,3,4]. both arrays sorted, have odd , numbers of elements respectively. so, piece of code taking account these 2 cases.

sorted indeed array. sort [2,3,1,4] , [1,2,3,4]. calculate middle index (len - 1) / 2 , len / 2 / odd number of elements, , find average of them.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -