secret
Last active

  • Download Gist
average_arrival.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 57
=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"])

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.