-
-
Save olivernn/b9c01abfc0c209113eb4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment