Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rainerthiel
Created October 13, 2009 00:40
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 rainerthiel/d577209112f1f7220dbd to your computer and use it in GitHub Desktop.
Save rainerthiel/d577209112f1f7220dbd to your computer and use it in GitHub Desktop.
=begin
The challenge wording leaves some things open so i will assume the following:
- Scheduled arrival can be any time of day or night.
- Arrival can only be late or on time, not early.
- When the arrival time is earlier than the scheduled arrival time
then that flight has arrived on the following day.
So the algorithm only works for arrival times that lie between
scheduled_arrival_time (on time) and 23:59 hours later.
Future challenge:
- Allow early arrivals.
- Allow more than 24h late or early.
=end
time = Regexp.new /([0-1][0-9]|2[0-3]):[0-5][0-9]/
def to_secs(time)
(time.slice(0..1).to_i * 3600) + (time.slice(3..4).to_i * 60)
end
def to_hhmm(secs)
daysecs = secs % (3600*24)
sprintf("%02d:%02d", (daysecs / 3600), (daysecs % 3600)/60)
end
########################
##### SCRIPT STARTS HERE #####
########################
begin
puts "Usage:"
puts "#{$0} <scheduled_arrival_time> <actual_arrival_time>..."
exit
end if ARGV.length < 2
if time.match(ARGV[0])
sched = to_secs(ARGV[0])
else
puts "#{ARGV[0]} is not a valid time. Please correct and run again"
exit
end
arrivals = []
delay_tot = 0
ARGV.delete_at(0) #remove the scheduled arrival time
ARGV.each do |arg|
if time.match(arg)
arriv = to_secs(arg)
delay = arriv - sched
delay += (24*60*60) if delay < 0
arrivals << [arriv, delay]
delay_tot += delay
else
puts("**** ERROR: Bad input time #{arg} rejected")
end
end
delay_avg = (delay_tot/arrivals.size).to_i
puts "\n\nFor scheduled arrival time #{to_hhmm(sched)}, given the following #{arrivals.size} actual arrival times:"
arrivals.each {|a| puts " => #{to_hhmm(a[0])} (delay #{to_hhmm(a[1]).slice(0..1)} hours and #{to_hhmm(a[1]).slice(3..4)} minutes)"}
puts "The average delay time is #{to_hhmm(delay_avg)}, arriving at #{to_hhmm(sched + delay_avg)}\n\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment