secret
anonymous / johnmcdonald.rb
Created

  • Download Gist
johnmcdonald.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#
# 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"])

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.