Skip to content

Instantly share code, notes, and snippets.

@sriram
Created October 18, 2009 12:31
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 sriram/00df2f1e36fbb0aa647e to your computer and use it in GitHub Desktop.
Save sriram/00df2f1e36fbb0aa647e to your computer and use it in GitHub Desktop.
=begin
Program to find the average arrival time
=end
require "rubygems"
require "parsedate"
class Average
def initialize
@sum = 0
@count = 0
@prev_day_hour = 0
@day = Time.now.day
end
##
# This method builds the date time objects based on the given input
# Assumption made here is that if the input times are 11:00pm, 12:01 am then the
# second time is given a different day.
# The first time will be: Sun Oct 18 23:00:00 +0530 2009
# The second time will be: Mon Oct 19 00:01:00 +0530 2009
# So this will work for any number of days.
#
def build_time_from_input(args)
times = []
args.each do |arg|
req_time = ParseDate.parsedate(arg)
req_time[0],req_time[1] = Time.now.year,Time.now.month
arg_day_hour = req_time[3]
req_time[2] = (((12..23) === @prev_day_hour) && ((0..11) === arg_day_hour)) ? (@day += 1) : @day
times << Time.local(*req_time)
@count += 1
@prev_day_hour = arg_day_hour
end
times
end
##
# This method contains the main logic
# From each datetime object generated from the above method, the first datetime object
# is subtracted. The average of these differences is then added to the first time.
#
def average_time_of_day(args)
times = build_time_from_input(args)
difference_times = []
first_time = times.first
times.each {|time| difference_times << (time-first_time) }
difference_times.each { |difference| @sum += difference }
"#{(first_time + @sum/@count).strftime("%l:%M %p")}"
end
end
average = Average.new
puts average.average_time_of_day(["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment