TheAlgorithms-Ruby/maths/average_median.rb

61 lines
2 KiB
Ruby
Raw Permalink Normal View History

2021-04-12 21:28:45 +02:00
# A ruby program to find average median
2021-04-15 01:36:21 +02:00
# Reference: https://dev.to/colerau/how-to-find-the-median-and-mean-of-an-array-in-ruby-4f04
2021-04-12 21:28:45 +02:00
module AverageMedian
def self.average_median(n, *array)
if n.instance_of? Integer
if n == array.size
array.sort
2021-09-03 22:24:58 +02:00
if array.size.even?
mid_element_1 = array.size / 2
2021-04-12 21:28:45 +02:00
mid_element_2 = mid_element_1 + 1
2021-04-15 01:39:13 +02:00
puts "The average median of the following elements #{array} is #{(array[mid_element_1 - 1] + array[mid_element_2 - 1]) / 2}."
2021-04-12 21:28:45 +02:00
else
2021-04-15 01:39:13 +02:00
mid_element = (array.size + 1) / 2
puts "The average median of the following elements #{array} is #{array[mid_element - 1]}."
2021-04-12 21:28:45 +02:00
end
else
puts "Provide the required #{n} elements properly!"
end
else
raise
end
2021-09-03 22:24:58 +02:00
rescue StandardError
puts 'Error: Please provide number only!'
2021-04-12 21:28:45 +02:00
end
end
2021-09-03 22:24:58 +02:00
#
2021-04-12 21:28:45 +02:00
# Valid inputs
2021-09-03 22:24:58 +02:00
#
2021-04-15 01:39:13 +02:00
puts AverageMedian.average_median(2, 3, 1)
# The average median of the following elements [3, 1] is 2.
puts AverageMedian.average_median(5, 1, 2, 3, 4, 5)
# The average median of the following elements [1, 2, 3, 4, 5] is 3.
puts AverageMedian.average_median(3, 2, 2, 2)
# The average median of the following elements [2, 2, 2] is 2.
2021-04-12 21:28:45 +02:00
2021-04-15 01:39:13 +02:00
puts AverageMedian.average_median(1, 5)
# The average median of the following elements [5] is 5.
2021-09-03 22:24:58 +02:00
#
2021-04-12 21:28:45 +02:00
# Invalid inputs
2021-09-03 22:24:58 +02:00
#
2021-04-15 01:39:13 +02:00
puts AverageMedian.average_median(2, 3, 1, 5)
# Provide the required 2 elements properly!
2021-09-03 22:24:58 +02:00
puts AverageMedian.average_median(2, 3, 'a')
2021-04-15 01:39:13 +02:00
# Traceback (most recent call last):
# 4: from /Users/voliveira/.rvm/rubies/ruby-2.7.0/bin/irb:23:in `<main>'
# 3: from /Users/voliveira/.rvm/rubies/ruby-2.7.0/bin/irb:23:in `load'
# 2: from /Users/voliveira/.rvm/rubies/ruby-2.7.0/lib/ruby/gems/2.7.0/gems/irb-1.2.1/exe/irb:11:in `<top (required)>'
# 1: from (irb):30
# NameError (undefined local variable or method `verageMedian' for main:Object)
2021-09-03 22:24:58 +02:00
puts AverageMedian.average_median('a', 1, 2)
2021-04-15 01:39:13 +02:00
# Error: Please provide number only!