Skip to content

Instantly share code, notes, and snippets.

@Noffica
Forked from davidvandusen/max.rb
Last active August 29, 2015 14:23
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 Noffica/f49ad90ed3c5e81481e8 to your computer and use it in GitHub Desktop.
Save Noffica/f49ad90ed3c5e81481e8 to your computer and use it in GitHub Desktop.
# # Find the maximum
# def maximum(arr)
# arr.max
# 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, 0, -3])
# puts "max of -23, 0, -3 is: #{result}"
# result = maximum([6])
# puts "max of just 6 is: #{result}"
##########################################################
def maximum(array)
i = 0
max_number = array[i]
index_of_max = i
while (i < (array.length))
if (max_number < array[i])
max_number = array[i]
index_of_max = i
end
i = i + 1
end
print "The highest number in the array, #{array}, is #{max_number}; which occurs at index position #{index_of_max}."
print "\n"
end
# Largest number at the end:
maximum([2, 42, 22, 02, 66])
# Largest number at the beginning:
maximum([222, 42, 22, 02, 66])
# Largest number somewhere in the middle:
maximum([222, 4200, 22, 02, 66])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment