secret
Last active

  • Download Gist
ahmedalhafoudh.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
require "time"
 
# Author: Ahmed Al Hafoudh <alhafoudh@freevision.sk>
# Date: 2009-10-09
 
def average_time_of_day(times)
last = Time.at(0) # keep last time
cum = sum = 0 # cum -> day span cumulation
# sum -> unixtime summary
times.each do |t|
tt = Time.parse(t) # get the Time class instance from the string
cum += 86400 if tt < last # if the time we are just parsing is before the time we parsed last time increment the day span cumulation by one day
sum += (tt + cum).to_i # sum the unixtime seconds
last = tt # set the new last time
end
 
Time.at(sum / times.length).strftime("%I:%M%p").downcase # calculate average time and format the output
end
 
if __FILE__ == $0
# Some simple test cases
# Input values from the text
puts average_time_of_day(["11:15pm", "12:03am", "11:30pm", "11:23pm" ,"11:48pm"])
# Code example on the page
puts average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"])
puts average_time_of_day(["6:41am", "6:51am", "7:01am"])
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.