Skip to content

Instantly share code, notes, and snippets.

Created October 9, 2009 04:11
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 anonymous/5cb7ba3254b511deaab7 to your computer and use it in GitHub Desktop.
Save anonymous/5cb7ba3254b511deaab7 to your computer and use it in GitHub Desktop.
# Solution for RPCFN 2: Average arrival time for a flight
# First I create a array with the list in minutes sorted
# Then I calculate the average of this elements
# I find the index looking for the closest value.
# using the formula: (average - item).abs to return a positive number,
# complementing with .min method to return the minimum value in array.
# With this value I search in array_in_minutes to get the index.
# Finally I use this index to show the element in the array list
require 'time'
def average_time_of_day( list )
list = list.sort!
array_in_minutes = list.collect{ |item| (Time.parse(item).hour * 60) + (Time.parse(item).min) }.sort!
sum_in_minutes = array_in_minutes.inject(0){ |result, element| result + element }
average = sum_in_minutes / list.length
min_value = array_in_minutes.collect{ |item| ( average - item ).abs }.min
index_position = array_in_minutes.collect{ |item| ( average - item ).abs }.index( min_value )
list[ index_position ]
end
a = ["6:41am", "6:51am", "7:01am"]
average_time_of_day(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment