Created
October 14, 2009 11:58
-
-
Save peterc/210008 to your computer and use it in GitHub Desktop.
A horribly scrappy solution to http://rubylearning.com/blog/2009/10/08/rpcfn-average-arrival-time-for-a-flight-2/
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
# 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