Get the mode value : Math extensions « Development « Ruby






Get the mode value


def mode(x)
  sorted = x.sort
  a = Array.new
  b = Array.new
  sorted.each do |x|
    if a.index(x)==nil
      a << x # Add to list of values
      b << 1 # Add to list of frequencies
    else
      b[a.index(x)] += 1 # Increment existing counter
    end
  end
  maxval = b.max           # Find highest count
  where = b.index(maxval)  # Find index of highest count
  a[where]                 # Find corresponding data value
end

data =[7,7,7,4,4,5,4,5,7,2,2,3,3,7,3,4 ]
puts mode(data)            # 7

 








Related examples in the same category

1.Add function to Math module
2.Your own math function
3.Get mean value
4.Get hmean value
5.Return the gmean value
6.Get the median value
7.Get variance value
8.Get sigma value