secret
anonymous / valeriofarias.rb
Last active

  • Download Gist
valeriofarias.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
# 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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.