secret
Last active

  • Download Gist
connerpeirce.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
# @author = Conner Peirce
 
require 'Time'
# assumes that times are within 13 hours of each other
# uses naive compare between current time and last time
def average_time_of_day( times, hourDiff = 13 )
day = 60*60*24 # in seconds
sum = 0
prevt= Time.parse(times[0]).to_f
for t in times do
parsedt = Time.parse(t).to_f
# if the new time is more than hourDiff from the last time
# then we assume that the day is off and add or subtract a day
if (parsedt-prevt).abs > (60*60*hourDiff)
if parsedt > prevt then nt = parsedt - day
else nt = parsedt + day
end
else nt = parsedt
end
sum+= nt
prevt = parsedt
end
Time.at(sum/times.length).strftime("%I:%M%p").downcase
end
 
p 'average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"])'
average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"])
p 'average_time_of_day(["6:41am", "6:51am", "7:01am"])'
average_time_of_day(["6:41am", "6:51am", "7:01am"])

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.