TheAlgorithms-Ruby/maths/find_max.rb

65 lines
1.8 KiB
Ruby
Raw Normal View History

2021-04-17 11:00:24 +02:00
# A ruby program to find max from a set of elements
2021-04-21 11:54:43 +02:00
# This find_max method will return the max element out of the array
2021-04-21 18:42:10 +02:00
def find_max(*array)
2021-04-21 11:54:43 +02:00
max = array[0]
array.each do |a|
if a >= max
max = a
2021-04-17 11:00:24 +02:00
end
end
2021-04-21 18:42:10 +02:00
"The Max of the following elements #{array} is #{max}."
2021-04-21 11:54:43 +02:00
rescue
2021-04-21 18:42:10 +02:00
"Error: Please provide number only!"
2021-04-21 11:54:43 +02:00
end
2021-04-17 11:00:24 +02:00
2021-04-21 11:54:43 +02:00
# Max method will return the maximum element from the set of input elements provided
2021-04-21 18:42:10 +02:00
def predefined_max(*array)
"The Max of the following elements #{array} is #{array.max}."
2021-04-21 11:54:43 +02:00
rescue
2021-04-21 18:42:10 +02:00
"Error: Please provide number only!"
2021-04-21 11:54:43 +02:00
end
2021-04-17 11:00:24 +02:00
2021-04-21 11:54:43 +02:00
# Sort method will sort the elements in ascending order. Last method will return the end element out of the array
2021-04-21 18:42:10 +02:00
def predefined_sort_last_max(*array)
"The Max of the following elements #{array} is #{array.sort.last}."
2021-04-21 11:54:43 +02:00
rescue
2021-04-21 18:42:10 +02:00
"Error: Please provide number only!"
2021-04-17 11:00:24 +02:00
end
# Using find_max
# Valid inputs
2021-04-21 11:54:43 +02:00
puts find_max(11, 29, 33)
2021-04-17 11:00:24 +02:00
# The Max of the following elements [11, 29, 33] is 33.
2021-04-21 11:54:43 +02:00
puts find_max(-221, -852, -1100, -10)
2021-04-17 11:00:24 +02:00
# The Max of the following elements [-221, -852, -1100, -10] is -10.
# Invalid inputs
2021-04-21 11:54:43 +02:00
puts find_max(5, "95", 2)
2021-04-17 11:00:24 +02:00
# Error: Please provide number only!
# Using predefined_max
# Valid inputs
2021-04-21 11:54:43 +02:00
puts predefined_max(51, 82, 39)
2021-04-17 11:00:24 +02:00
# The Max of the following elements [51, 82, 39] is 82.
2021-04-21 11:54:43 +02:00
puts predefined_max(-11, -51, -10, -10)
2021-04-17 11:00:24 +02:00
# The Max of the following elements [-11, -51, -10, -10] is -10.
# Invalid inputs
2021-04-21 11:54:43 +02:00
puts predefined_max("x", 5, 95, 2)
2021-04-17 11:00:24 +02:00
# Error: Please provide number only!
# Using predefined_sort_last_max
# Valid inputs
2021-04-21 11:54:43 +02:00
puts predefined_sort_last_max(1, 2, 3)
2021-04-17 11:00:24 +02:00
# The Max of the following elements [1, 2, 3] is 3.
2021-04-21 11:54:43 +02:00
puts predefined_sort_last_max(-21, -52, -100, -1)
2021-04-17 11:00:24 +02:00
# The Max of the following elements [-21, -52, -100, -1] is -1.
# Invalid inputs
2021-04-21 11:54:43 +02:00
puts predefined_sort_last_max(5, 95, 2, "a")
2021-04-17 11:00:24 +02:00
# Error: Please provide number only!