Skip to content

Instantly share code, notes, and snippets.

/bradoconnor.rb Secret

Created October 12, 2009 10:33
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/7214b8695201d8d53ea0 to your computer and use it in GitHub Desktop.
Save anonymous/7214b8695201d8d53ea0 to your computer and use it in GitHub Desktop.
require 'time'
class FlightTimes
attr_reader :times
def initialize (times)
@times = times
end
def sort!
@times.sort!
end
def best_start_time #Returns the index number of the @times array that gives the shortest interval between start and end times
times_array = @times
result_array = []
times_array.each do
result_array << times_array.last - times_array.first
self.cycle_times
end
result_array.index(result_array.min)
end
def cycle_times #Cycles the array of @times so the first time becomes the last and is advanced to tomorrow
@times << @times.shift+86400
end
def mean
sum=0.0
@times.each {|time| sum += time.to_f}
sum/@times.length
end
end
def average_time_of_day(timestrings)
times=[]
timestrings.each do |time|
if (time.class != String or (time =~ /([0-9]|01|02|03|04|05|06|07|08|09|10|11|12):[0-5]\d[a|p]m/) != 0)
raise ArgumentError
end
times << Time.parse(time)
end
flight_times = FlightTimes.new(times)
flight_times.sort!
flight_times.best_start_time.times do
flight_times.cycle_times
end
Time.at(flight_times.mean).strftime("%I:%M%p").sub(/^0/,"").downcase
rescue ArgumentError
"Invalid times entered. Times must be entered as an array of strings in 12 hour format with no leading zero, i.e. the format h:mm(am/pm), eg 1:20pm, 10:30am etc."
end
puts average_time_of_day(ARGV) unless ARGV.empty?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment