Skip to content
Create a gist now

Instantly share code, notes, and snippets.

anonymous /johnmcdonald.rb secret
Created Oct 17, 2009

# 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 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)
def calc_average_time(arrival_times)
avg_time = 0
start_time =
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
# 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)
avg_time += arrival_time - start_time
#puts start_time, arrival_time, avg_time
raise "Bad time entered: check input " unless number_of_times == arrival_times.size
(start_time + avg_time/arrival_times.size).strftime("%I:%M%p")
#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.