secret
Last active

  • Download Gist
olivernn.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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
#
# This script was written for the ruby learning blog challenge
# http://rubylearning.com/blog/2009/10/08/rpcfn-average-arrival-time-for-a-flight-2/
#
# The script will calculate the average arrival time from an array of given arrival times.
# It is assumed that the arrival times will be in the format HH:MM and be in the 12hour clock
# format with a 2 digit meridiem. The hours do not need to be padded to fill 2 digits, e.g. 6:51pm is valid
#
# For the script to work the arrival times MUST be in order, starting with the earliest ever arrival time.
# For cases where arrival times span more than one day it is assumed that the first time is the earliest
# time in a calendar sense. For example if the flight arrived on Friday at 23:59 and Saturday at 00:01
# then they should be entered into the array as follows ["11:59pm", "12:01am"]
#
# It is also assumed that 1 minute past midnight would be represented as 12:01am
#
# Finally, it is assumed that the airline can never be more than 24 hours late
 
arrival_times = ["11:51pm", "11:56pm", "12:01am", "12:06am", "12:11am"] # put your times in this array
 
class ArrivalTime
attr_accessor :hours, :minutes, :meridiem, :twelve_hour
def initialize(time)
@time = time
@twelve_hour = true
parse
convert_to_24hr
end
def convert_to_24hr
if meridiem == "pm"
self.hours = hours + 12
else
self.hours = hours - 12 if hours >= 12
end
self.twelve_hour = false
end
def to_sec
(hours * 3600) + (minutes * 60)
end
def add_24hrs
self.hours = hours + 24
end
private
def parse
time_array = @time.split(":")
self.hours = time_array[0].to_i
self.minutes = time_array[1].to_i
self.meridiem = time_array[1].gsub(/[0-9]{2}/, "")
end
end
 
# monkey patching array so that it can sum and then average the arrival times
class Array
def sum_times
inject(0) {|sum, arrival_time| sum + arrival_time.to_sec}
end
def average
sum_times / size
end
end
 
 
# start looping through the input arrival times
 
arrival_times.collect! do |t|
ArrivalTime.new(t)
end
 
arrival_times.each_with_index do |time, i|
unless i == 0
if time.hours < arrival_times[i-1].hours
time.add_24hrs
end
end
end
 
average_arrival_time = Time.at(arrival_times.average - 3600) # since epoch was at 01:00 we need to take away an hour
 
puts "The average arrival time is " + average_arrival_time.strftime("%I:%M%p")

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.