secret
Last active

  • Download Gist
jonathanjulian.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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
require 'time'
 
#
# Compute the average time from a list of times.
#
# http://rubylearning.com/blog/2009/10/08/rpcfn-average-arrival-time-for-a-flight-2/
#
# ASSUMPTIONS
# * input error checking is left out. inputs are assumed to be in format h:m[am/pm], parsable by Time
#
# SOLUTION
# Convert all the inputs to today. Then average them as seconds sinch epoch and format the result.
#
# Since the times may span across midnight, we need to know what the user's idea of the "cutoff" is.
# In the given example, the flight is scheduled to arrive at 10pm, so if it's 3 hours late, 1am
# should be considered the next day. Heck, if it's 22 hours late, 8pm should be considered the next
# day! So by default, the cutoff is set to 10:00pm. (A cutoff of 12:00am would mean all times should
# be considered the same day). The 10pm flight example will still work even with a cutoff in the early
# evening (like 6pm), which will then compute properly for flights arriving early.
#
def average_time_of_day(time_strings, cutoff_string="10:00pm")
avg = time_strings.collect do |time_string|
time = Time.parse(time_string)
if time < Time.parse(cutoff_string)
time += (60*60*24) # it's after midnight - make it the next day
end
time.to_i
end.average
Time.at(avg).strftime('%I:%M%p').downcase.gsub(/^0/,'')
end
 
# add an average method to Array. not a robust implementation.
class Array
def average
self.inject(0) {|sum,v| sum += v.to_f} / self.size
end
end
 
 
require 'test/unit'
 
class ChallengeTest < Test::Unit::TestCase
def test_example_1
assert_equal("12:01am", average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"]))
end
def test_example_2
assert_equal("6:51am", average_time_of_day(["6:41am", "6:51am", "7:01am"]))
end
def test_kalle_example
# comment by Kalle Lindström
assert_equal("9:37am", average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"], "12:00am"))
end
def test_average
assert_equal(5, [1,3,5,7,9].average)
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.