Skip to content

Instantly share code, notes, and snippets.

@peterc
Created October 14, 2009 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterc/210008 to your computer and use it in GitHub Desktop.
Save peterc/210008 to your computer and use it in GitHub Desktop.
# A horribly scrappy "just for fun" entry into Satish Talim's latest Ruby
# challenge. Didn't want to use any libraries, etc, just bashed at it true 1980s style!
# It makes the assumption, as was raised in several comments, that the first time in
# the array is the first of the "block" of times..
def average_time_of_day(times)
pr = nil
times.map! do |t|
h,m = t.scan(/\d+/).map(&:to_i)
h += 12 if t =~ /pm/ || (pr && h < pr)
pr = h
h + m / 60.0
end
mean = times.reduce(:+) / times.size
h = mean.to_i
m = sprintf("%0.2d", ((mean - h) * 60.0).round)
"#{h > 12 ? h - 12 : h}:#{m}#{ h > 12 && h != 24 ? 'pm' : 'am' }"
end
raise unless average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"]) == "12:01am"
raise unless average_time_of_day(["6:41am", "6:51am", "7:01am"]) == "6:51am"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment