Skip to content

Instantly share code, notes, and snippets.

@danhealy
Last active January 2, 2019 17:17
Show Gist options
  • Save danhealy/4cd8df40355426ecbdbad7fdbd017575 to your computer and use it in GitHub Desktop.
Save danhealy/4cd8df40355426ecbdbad7fdbd017575 to your computer and use it in GitHub Desktop.
Average of an array, and removing outliers
# Initialize an array of 50 random integers. If you know ahead of time that the
# elements will be unique, use Set class instead for performance improvements
array = Array.new(50) do rand(100) end
# Ruby 2.4 and later has the Array#sum method which could also be implemented as
# a simple #inject call in earlier versions, it's also mixed in with Rails
avg = array.sum / array.length.to_f # to_f required for float precision
# Removing the min and max of the array by sorting. This particular method
# won't work if the original array is less than 3 elements.
outlier_removed_avg = array.sort[1..-2].sum / (array.length - 2).to_f
# Or by using Array#minmax which returns the min and max values, and removing
# those from the original array prior to calculating average
outlier_removed_array = array - array.minmax
# The above won't work if the min and max values are repeated, since #- will
# remove all matching elements. In this case you need to remove the min value
# and max value separately (#dup used to save original):
outlier_removed_array = array.dup
outlier_removed_array.minmax.each do |i|
outlier_removed_array.delete_at(outlier_removed_array.index(i))
end
outlier_removed_avg = outlier_removed_array.sum / outlier_removed_array.length.to_f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment