Created
October 19, 2009 01:07
-
-
Save bmarini/212996 to your computer and use it in GitHub Desktop.
Solution to RPCFN #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
module AverageTimeOfDay | |
require 'date' | |
# Assumes times_of_day is an array of valid time strings in chronological | |
# order. | |
def average_time_of_day(times_of_day) | |
# Convert times_of_day to an array of Time objects, ensuring that times | |
# are in chronological order by adding a day if the the time of the | |
# current iteration is earlier than the last iterated time. | |
times = times_of_day.inject([]) do |times, time_of_day| | |
dt = DateTime.strptime(time_of_day, "%I:%M%p") | |
time = Time.local( dt.year, dt.month, dt.day, dt.hour, dt.min ) | |
time += ( 60 * 60 * 24 ) if times.last && times.last > time | |
times.push(time) | |
end | |
# Compute the average time | |
average_time = times.inject(0) {|m,t| m + t.to_i } / times.size | |
# Format the average time | |
Time.at(average_time).strftime("%I:%M%p").downcase.gsub(/^0/, '') | |
end | |
end | |
# Execute tests if this file is run by itself. | |
if $0 == __FILE__ | |
require "test/unit" | |
include AverageTimeOfDay | |
class TestAverageTimeOfDay < Test::Unit::TestCase | |
def test_average_time_of_day | |
assert_equal "12:01am", average_time_of_day( | |
["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"] ) | |
assert_equal "6:51am", average_time_of_day( | |
["6:41am", "6:51am", "7:01am"] ) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment