Skip to content
Create a gist now

Instantly share code, notes, and snippets.

require 'time'
# Compute the average time from a list of times.
# * input error checking is left out. inputs are assumed to be in format h:m[am/pm], parsable by Time
# 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
# 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
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"]))
def test_example_2
assert_equal("6:51am", average_time_of_day(["6:41am", "6:51am", "7:01am"]))
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"))
def test_average
assert_equal(5, [1,3,5,7,9].average)
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.