-
-
Save anonymous/5cb7ba3254b511deaab7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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