Skip to content

anonymous /johnmcdonald.rb secret

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
#
# average_time_of_day(arrival_times)
# arrival_times is an array of times, e.g
# ["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"]
# code calculates the average of the array of the times of day
#
# start time is implied to be any time of day, am or pm, so
# the code will work just using Time.now as a start time
# if start time is 'am' all times are assumed to be the same day
# if start time is 'pm' all 'am' times are assumed to be the next day
#
require 'time'
def average_time_of_day(arrival_times)
calc_average_time(arrival_times)
end
def calc_average_time(arrival_times)
avg_time = 0
start_time = Time.now
am_or_pm = start_time.strftime("%p").downcase
number_of_times = 0
arrival_times.each { |item| item.gsub(/^([0]*[1-9]|[1][0-2]):([0-9]{2})([a|p]m)/) do
arrival_time = Time.parse($1 + ":" + $2 + $3)
number_of_times = number_of_times + 1
case
# add a day if time is 'am' and start time is in the 'pm'
when am_or_pm == "pm" && $3 == "am" then arrival_time += (60 * 60 * 24)
end
avg_time += arrival_time - start_time
#puts start_time, arrival_time, avg_time
end
}
raise "Bad time entered: check input " unless number_of_times == arrival_times.size
(start_time + avg_time/arrival_times.size).strftime("%I:%M%p")
end
#p average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.