Skip to content

Instantly share code, notes, and snippets.

Created October 20, 2009 14:19
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 anonymous/cf6b3e6330e6da8c102f to your computer and use it in GitHub Desktop.
Save anonymous/cf6b3e6330e6da8c102f to your computer and use it in GitHub Desktop.
require 'time'
def average_time_of_day(allTimes)
times = convert_strings_to_times(allTimes)
average_time = compute_average_time(times)
return format_time(average_time)
end
def convert_strings_to_times(strings)
times = strings.map do |str|
time = Time.parse(str)
# "AM" dates should be consided one day after "PM" dates
time += 60 * 60 * 24 if str =~ /am/
time
end
times
end
def compute_average_time(times)
times_as_integer = times.map { |time| time.to_i }
mean = times_as_integer.inject('+') / times_as_integer.length
return Time.at(mean)
end
def format_time(time)
time.strftime("%I:%M%P").gsub(/^0/, "")
end
require 'test/unit'
require 'average_time_of_day'
class TestAverageTimeOfDay < Test::Unit::TestCase
def test_multiple_times
assert_equal("5:59pm", average_time_of_day(["11:58pm", "12:00pm"]))
assert_equal("6:51am", average_time_of_day(["6:41am", "6:51am", "7:01am"]))
assert_equal("12:01am", average_time_of_day(["11:51pm", "12:06am", "12:01am","11:56pm", "12:11am"]))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment