Noffica
6/23/2015 - 6:47 PM

max.rb

# # 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])