Merge pull request #131 from msaf9/master

PR for find max feature
This commit is contained in:
Vitor Oliveira 2021-04-22 08:34:57 -07:00 committed by GitHub
commit 40460108af
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 65 additions and 0 deletions

View file

@ -79,6 +79,7 @@
* [Decimal To Binary](https://github.com/TheAlgorithms/Ruby/blob/master/maths/decimal_to_binary.rb)
* [Factorial](https://github.com/TheAlgorithms/Ruby/blob/master/maths/factorial.rb)
* [Fibonacci](https://github.com/TheAlgorithms/Ruby/blob/master/maths/fibonacci.rb)
* [Find Max](https://github.com/TheAlgorithms/Ruby/blob/master/maths/find_max.rb)
* [Number Of Digits](https://github.com/TheAlgorithms/Ruby/blob/master/maths/number_of_digits.rb)
* [Power Of Two](https://github.com/TheAlgorithms/Ruby/blob/master/maths/power_of_two.rb)
* [Prime Number](https://github.com/TheAlgorithms/Ruby/blob/master/maths/prime_number.rb)

64
maths/find_max.rb Normal file
View file

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