Create a gist now

Instantly share code, notes, and snippets.

anonymous /valeriofarias.rb Secret
Created Oct 9, 2009

# 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 ]
a = ["6:41am", "6:51am", "7:01am"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment