Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@garrettgsb
Created April 26, 2016 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garrettgsb/1d8f4f86a9ebcc00778c1918b309c876 to your computer and use it in GitHub Desktop.
Save garrettgsb/1d8f4f86a9ebcc00778c1918b309c876 to your computer and use it in GitHub Desktop.
Maximum Value
# 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