Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
require 'test/unit'
class ArrivalTime
def convert_to_24h(time)
if time =~ %r{(\d+):(\d+)pm$}
h, m = "%02d" % ($1.to_i+12), $2
"#{h}#{m}"
elsif time =~ %r{(\d+):(\d+)am$}
h = $1.to_i
h = 0 if h == 12
h, m = ("%02d" % h), $2
"#{h}#{m}"
end
end
def convert_from_24h(time)
if time =~ %r{(\d\d)(\d\d)}
h, m = $1.to_i, $2.to_i
if h > 11
am_or_pm = "pm"
h = h - 12
else
am_or_pm = "am"
end
"#{"%d" % h}:#{"%02d" % m}#{am_or_pm}"
end
end
def average(times)
first = times.first.to_i
seconds = times.inject(0) do |sum, n|
convert_to_seconds(n) + sum
end / times.size
convert_from_seconds(seconds)
end
def convert_to_seconds(time)
if time =~ %r{^(\d\d)(\d\d)$}
hour, minute = $1.to_i, $2.to_i
(hour * 60 * 60) + (minute * 60)
end
end
def convert_from_seconds(seconds)
hours = seconds / (60 * 60)
seconds = seconds - (hours * 60 * 60)
minutes = seconds / 60
"#{"%02d" % hours}#{"%02d" % minutes}"
end
def convert_and_average(times)
converted_times = times.map do |time|
time = convert_to_24h(time)
end
average_time = average(converted_times)
convert_from_24h(average_time)
end
end
def average_time_of_day(times)
arrival_time = ArrivalTime.new
arrival_time.convert_and_average(times)
end
class ArrivalTimeTest < Test::Unit::TestCase
def setup
@arrival_time = ArrivalTime.new
end
def test_convert_time_to_24h
assert_equal "2351", @arrival_time.convert_to_24h("11:51pm")
assert_equal "1150", @arrival_time.convert_to_24h("11:50am")
assert_equal "1000", @arrival_time.convert_to_24h("10:00am")
assert_equal "0500", @arrival_time.convert_to_24h("5:00am")
end
def test_convert_24h_to_time
assert_equal "11:51pm", @arrival_time.convert_from_24h("2351")
assert_equal "11:50am", @arrival_time.convert_from_24h("1150")
assert_equal "10:00am", @arrival_time.convert_from_24h("1000")
assert_equal "5:00am", @arrival_time.convert_from_24h("0500")
end
def test_should_average_an_array_of_times_that_dont_cross_date_boundaries
times = %w[1101 1107]
assert_equal "1104", @arrival_time.average(times)
times =%w[2142 2148]
assert_equal "2145", @arrival_time.average(times)
end
def test_convert_time_to_seconds
{"0005" => 300, "1306" => 47_160, "2237" => 81_420}.each_pair do |k,v|
assert_equal v, @arrival_time.convert_to_seconds(k)
end
end
def test_convert_seconds_to_time
{"0005" => 300, "1306" => 47_160, "2237" => 81_420}.each_pair do |k,v|
assert_equal k, @arrival_time.convert_from_seconds(v)
end
end
def test_averaging_times_in_same_day
assert_equal "6:51am", average_time_of_day(["6:41am", "6:51am", "7:01am"])
end
def test_averaging_times_across_a_date_boundary
assert_equal "9:37am", average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "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.