Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating Median in Ruby

Tags:

ruby

median

How do I calculate the median of an array of numbers using Ruby?

I am a beginner and am struggling with handling the cases of the array being of odd and even length.

like image 826
tbone Avatar asked Feb 13 '13 17:02

tbone


People also ask

How to calculate median in Ruby?

Assuming the array has an odd amount of numbers, we can find the median by taking the sorted array and finding the element at (count/2). floor . The . floor rounds down to the nearest integer and is essential to get the right answer.

How do you remove an empty string from an array in Ruby?

Use compact_blank to remove empty strings from Arrays and Hashes.


2 Answers

Here is a solution that works on both even and odd length array and won't alter the array:

def median(array)   return nil if array.empty?   sorted = array.sort   len = sorted.length   (sorted[(len - 1) / 2] + sorted[len / 2]) / 2.0 end 
like image 90
nbarraille Avatar answered Sep 20 '22 22:09

nbarraille


If by calculating Median you mean this

Then

a = [12,3,4,5,123,4,5,6,66] a.sort! elements = a.count center =  elements/2 elements.even? ? (a[center] + a[center+1])/2 : a[center]   
like image 27
AnkitG Avatar answered Sep 24 '22 22:09

AnkitG