Skip to content

@bmarini /average_time_of_day.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

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