Skip to content

anonymous /TestAverageTimeOfDay.rb secret
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.