Skip to content

Instantly share code, notes, and snippets.

@jjulian
Created October 8, 2009 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjulian/562ae4d9557bc351d451 to your computer and use it in GitHub Desktop.
Save jjulian/562ae4d9557bc351d451 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment