-
-
Save conner/0b7d4e13599fa65db6bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# @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"]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment