Instantly share code, notes, and snippets.

# anonymous/valeriofarias.rbSecret Created Oct 9, 2009

What would you like to do?
 # 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)