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.
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.
Use compact_blank to remove empty strings from Arrays and Hashes.
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With