Skip to content

Instantly share code, notes, and snippets.

/davidjenkins.rb Secret

Created October 9, 2009 19:55
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 anonymous/44593f6efc6c463880ab to your computer and use it in GitHub Desktop.
Save anonymous/44593f6efc6c463880ab to your computer and use it in GitHub Desktop.
=begin
Purpose:write method average_time_of_day that takes an array of times in format "hh:mm(am|pm)"
and returns the average time of those times in the same format
e.g.,
>> average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"])
=> "12:01am"
Notes : program assumes that the first time in the array is the earliest actual time in the array
Author: David Jenkins
=end
require 'time'
ONE_DAY_IN_SECONDS = (60 * 60 * 24)
def average_time_of_day times
first_time = nil
time_sum = 0
times.each do |t|
mil_time = Time.parse(t)
first_time ||= mil_time
if mil_time < first_time
mil_time+= ONE_DAY_IN_SECONDS
end
time_sum += mil_time.to_i
end
Time.at(time_sum / times.size).strftime("%I:%M%p").downcase
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment