Created
April 26, 2016 19:53
-
-
Save garrettgsb/1d8f4f86a9ebcc00778c1918b309c876 to your computer and use it in GitHub Desktop.
Maximum Value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Find the maximum | |
def maximum(arr) | |
# My first method... Uses 0 as a default value, so | |
# kind of doesn't work for an array full of elements | |
# that are less than zero. | |
y = 0 | |
arr.each do |x| | |
if x > y | |
y = x | |
end | |
end | |
return y | |
# Second way using "inject" -> No default value; returns nil | |
# for empty array. Also looks succinct and pretty. | |
#arr.inject{|y,x| x > y ? x : y} | |
end | |
# expect it to return 42 below | |
result = maximum([2, 42, 22, 02]) | |
puts "max of 2, 42, 22, 02 is: #{result}" | |
# expect it to return nil when empty array is passed in | |
result = maximum([]) | |
puts "max on empty set is: #{result.inspect}" | |
result = maximum([-23, -1, -3]) | |
puts "max of -23, -1, -3 is: #{result}" | |
result = maximum([6]) | |
puts "max of just 6 is: #{result}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment