Create a gist now

Instantly share code, notes, and snippets.

Adam Lum's solution to RPCFN #2 (Average Arrival Time for a Flight)
# Adam Lum's solution to RPCFN #2
# http://rubylearning.com/blog/2009/10/08/rpcfn-average-arrival-time-for-a-flight-2/
require 'time'
SECONDS_TO_CHECK_FOR = 10800 # Assuming 3 hours is a decent difference check
SECONDS_IN_DAY = 86400
def average_time_of_day(times)
count_greater = 0
total = 0
previous_time_seconds = 0
seconds_array = []
times.each do |time|
seconds_array << Time.parse(time).to_i
end
seconds_array.sort!
seconds_array.each do |s|
if (previous_time_seconds != 0)
if ((s - previous_time_seconds).abs >= SECONDS_TO_CHECK_FOR)
count_greater += 1
end
end
previous_time_seconds = s
end
if (count_greater > 0)
if (count_greater >= (times.size / 2))
previous_time_seconds = 0
(0..seconds_array.size - 1).each do |i|
if ((seconds_array[i] - previous_time_seconds).abs >= SECONDS_TO_CHECK_FOR)
seconds_array[i] -= SECONDS_IN_DAY
end
previous_time_seconds = seconds_array[i]
end
else
previous_time_seconds = 0
(0..seconds_array.size - 1).each do |i|
if ((seconds_array[i] - previous_time_seconds).abs >= SECONDS_TO_CHECK_FOR)
previous_time_seconds = 0
(0..seconds_array.size - 1).each do |i|
if ((seconds_array[i] - previous_time_seconds).abs >= SECONDS_TO_CHECK_FOR)
seconds_array[i] += SECONDS_IN_DAY
end
previous_time_seconds = seconds_array[i]
end
end
end
end
end
Time.at(seconds_array.inject {|sum,n| sum += n } / times.size).strftime("%I:%M%p").downcase
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment