secret
Last active

  • Download Gist
rainerthiel.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
=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"

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.