51

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

I am a beginner and within the progress of my learning I am trying to stick to what has already been taught. Thus the other questions that I've found are beyond my scope.

Here are my notes and my attempt:

  1. sort the array in ascending order.
  2. figure out if it is odd or even in length.
  3. if odd, divide the sorted array length +1 in half. That is the index of the median. Return this value.
  4. if even, find the middle two numbers of the sorted array and divide them in 1/2. Return this value.
  5. Finding the middle two numbers:
  6. divide the sorted array length in half. This is index pt. first middle number.
  7. divide sorted array length + 2 in half. This is the index pt. of the second middle number.
  8. take average of these two middle numbers.

    def median(array)
      ascend = array.sort
      if ascend % 2 != 0
        (ascend.length + 1) / 2.0
      else
        ((ascend.length/2.0) + ((ascend.length + 2)/2.0) / 2.0)
      end
    end
    
Morgan
  • 18,407
  • 6
  • 54
  • 78
tomgalpin
  • 812
  • 1
  • 7
  • 17

11 Answers11

101

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
nbarraille
  • 9,158
  • 14
  • 60
  • 92
4

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]  
AnkitG
  • 6,068
  • 6
  • 40
  • 69
  • yeah, the even number one makes it an if ... else procedure (in what I've learned so far) – tomgalpin Feb 13 '13 at 17:37
  • Doesn't have to have a if/else, see my answer – nbarraille Feb 13 '13 at 17:39
  • Needs `2.0` or a `to_f` to make results like 4.5 possible. – steenslag Feb 13 '13 at 18:30
  • 2
    Additionally the final line should be `elements.even? ? (a[center] + a[center-1])/2.0 : a[center]` (note the minus in `a[center-1]` and the `2.0`) otherwise the median value of an even-length array is offset by 1 index position in the array. Try the original code with a 2-value array and you will get an error. This just bit me... – djoll Nov 06 '13 at 12:25
2

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
Kal
  • 1,025
  • 7
  • 19
2
  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
1

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
Alexander
  • 397
  • 4
  • 9
0
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

user3007294
  • 901
  • 12
  • 27
0
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])
Zoh
  • 57
  • 5
0

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

m02ph3u5
  • 2,735
  • 6
  • 34
  • 45
Nana
  • 11
  • 2
0
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
0

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
Victor
  • 671
  • 9
  • 10
-2

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: Sorting an array in descending order in Ruby.

Community
  • 1
  • 1
whatzzz
  • 1
  • 1