user142019
user142019

Reputation:

Finding the highest, lowest, total, average and median from an array in Ruby

I am creating a boxplot generator in Ruby, and I need to calculate some things.

Let's say I have this array:

arr = [1, 5, 7, 2, 53, 65, 24]

How can I find the lowest value (1), highest value (65), total (157), average (22.43) and median (7) from the above array?

Thanks

Upvotes: 30

Views: 34104

Answers (2)

Fryie
Fryie

Reputation: 146

Finding the minimum, maximum, sum and average are trivial and can be done easily in linear time as shown by sepp2k's answer above.

Finding the median is less trivial and the naive implementation (sorting, and then taking the middle element) runs in O(nlogn) time.

There are, however, algorithms that find the median in linear time (such as the median-of-5 algorithm). Others work even for any kind of order statistic (say, you want to find the 5th-smallest element). The problem with those is that you would have to implement them yourself, I know of no Ruby implementation.

O(nlogn) is quite fast already, so if you're not planning on working on huge datasets (and if you will need to sort your data anyway), you'll be fine with that.

Upvotes: 1

sepp2k
sepp2k

Reputation: 370357

lowest = arr.min
highest = arr.max
total = arr.inject(:+)
len = arr.length
average = total.to_f / len # to_f so we don't get an integer result
sorted = arr.sort
median = len % 2 == 1 ? sorted[len/2] : (sorted[len/2 - 1] + sorted[len/2]).to_f / 2

Upvotes: 66

Related Questions