Calculating Median in Ruby

RubyMedian

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

Similar to nbarraille's, but I find it a bit easier to keep track of why this one works:

class Array
  def median
    sorted = self.sort
    half_len = (sorted.length / 2.0).ceil
    (sorted[half_len-1] + sorted[-half_len]) / 2.0
  end
end

half_len = number of elements up to and including (for array with odd number of items) middle of array.

Even simpler:

class Array
  def median
    sorted = self.sort
    mid = (sorted.length - 1) / 2.0
    (sorted[mid.floor] + sorted[mid.ceil]) / 2.0
  end
end

Solution 3 - Ruby

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]  

Solution 4 - Ruby

  def median(array)                          #Define your method accepting an array as an argument. 
      array = array.sort                     #sort the array from least to greatest
      if array.length.odd?                   #is the length of the array odd?
        array[(array.length - 1) / 2] #find value at this index
      else array.length.even?                #is the length of the array even?
       (array[array.length/2] + array[array.length/2 - 1])/2.to_f
                                             #average the values found at these two indexes and convert to float
      end
    end

Solution 5 - Ruby

More correct solution with handling edge cases:

class Array
  def median
    sorted = self.sort
    size = sorted.size
    center = size / 2

    if size == 0
      nil
    elsif size.even?
      (sorted[center - 1] + sorted[center]) / 2.0
    else
      sorted[center]
    end
  end
end

There is a specs to prove:

describe Array do
  describe '#median' do
    subject { arr.median }

    context 'on empty array' do
      let(:arr) { [] }

      it { is_expected.to eq nil }
    end

    context 'on 1-element array' do
      let(:arr) { [5] }

      it { is_expected.to eq 5 }
    end

    context 'on 2-elements array' do
      let(:arr) { [1, 2] }

      it { is_expected.to eq 1.5 }
    end

    context 'on odd-size array' do
      let(:arr) { [100, 5, 2, 12, 1] }

      it { is_expected.to eq 5 }
    end

    context 'on even-size array' do
      let(:arr) { [7, 100, 5, 2, 12, 1] }

      it { is_expected.to eq 6 }
    end
  end
end

Solution 6 - Ruby

I like to use Refinements, which is a safe way to Monkey Patch the ruby classes without collateral effects over the system.

The usage become much more cleaner than a new method.

With the Refinements you can monkey patch the Array class, implement the Array#median and this method will only be available inside the scope of the class that is using the refinement! :)

Refinements
module ArrayRefinements
  refine Array do
    def median
      return nil if empty?
      sorted = sort
      (sorted[(length - 1) / 2] + sorted[length / 2]) / 2.0
    end
  end
end

class MyClass
  using ArrayRefinements
  # You can use the Array#median as you wish here

  def test(array)
    array.median
  end
end

MyClass.new.test([1, 2, 2, 2, 3])
=> 2.0

Solution 7 - Ruby

def median(array)
  half = array.sort!.length / 2
  array.length.odd? ? array[half] : (array[half] + array[half - 1]) / 2 
end

*If the length is even, you must add the middle point plus the middle point - 1 to account for the index starting at 0

Solution 8 - Ruby

def median(arr)
    sorted = arr.sort 
    if sorted == []
       return nil
    end  

    if sorted.length % 2 != 0
       result = sorted.length / 2 # 7/2 = 3.5 (rounded to 3)
       return sorted[result] # 6 
    end
      
    if sorted.length % 2 == 0
       result = (sorted.length / 2) - 1
       return (sorted[result] + sorted[result+1]) / 2.0 #  (4 + 5) / 2
    end
end

p median([5, 0, 2, 6, 11, 10, 9])

Solution 9 - Ruby

Here's a solution:

app_arry = [2, 3, 4, 2, 5, 6, 16].sort

# check array isn't empty
if app_arry.empty?  || app_arry == ""
  puts "Sorry, This will not work."
  return nil
end

length = app_arry.length
puts "Array length = #{length}"
puts "Array = #{app_arry}"

if length % 2  == 0
 # even number of elements
 puts "median is #{(app_arry[length/2].to_f +  app_arry[(length-1)/2].to_f)/2}"
else
 # odd number of elements
 puts "median is #{app_arry[(length-1)/2]}"
end

OUTPUT

> Array length = 7 > > Array = [2, 3, 4, 2, 5, 6, 16] > > median is 2

Solution 10 - Ruby

def median(array, already_sorted=false)
    return nil if array.empty?
    array = array.sort unless already_sorted
    m_pos = array.size / 2
    return array.size % 2 == 1 ? array[m_pos] : mean(array[m_pos-1..m_pos])
end

Solution 11 - Ruby

I think it's good:

#!/usr/bin/env ruby

#in-the-middle value when odd or
#first of second half when even.
def median(ary)
  middle = ary.size/2
  sorted = ary.sort_by{ |a| a }
  sorted[middle]
end

or

#in-the-middle value when odd or
#average of 2 middle when even.
def median(ary)
  middle = ary.size/2
  sorted = ary.sort_by{ |a| a }
  ary.size.odd? ? sorted[middle] : (sorted[middle]+sorted[middle-1])/2.0
end

I used sort_by rather than sort because it's faster: https://stackoverflow.com/questions/2642182/sorting-an-array-in-descending-order-in-ruby.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontboneView Question on Stackoverflow
Solution 1 - RubynbarrailleView Answer on Stackoverflow
Solution 2 - RubyKalView Answer on Stackoverflow
Solution 3 - RubyAnkitGView Answer on Stackoverflow
Solution 4 - RubyKyle Snow SchwartzView Answer on Stackoverflow
Solution 5 - RubyAlexanderView Answer on Stackoverflow
Solution 6 - RubyVictorView Answer on Stackoverflow
Solution 7 - Rubyuser3007294View Answer on Stackoverflow
Solution 8 - RubyZohView Answer on Stackoverflow
Solution 9 - RubyNanaView Answer on Stackoverflow
Solution 10 - RubyYashvi PatelView Answer on Stackoverflow
Solution 11 - RubywhatzzzView Answer on Stackoverflow