secret
Created

  • Download Gist
TestAverageTimeOfDay.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11
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
average_time_of_day.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.