public
Last active

Solution to RPCFN #2

  • Download Gist
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 33 34 35 36 37 38 39
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.