This is my first time writing ruby - and I was mainly hoping to get some feedback and stylistic pointers.
The algorithm is pretty straight-forward, since Google guarantees airports aren't repeated I store all the tickets in a hash table and then sort from random insertion points, which should be worst case \$O(n \log n)\$.
Once upon a day, Mary bought a one-way ticket from somewhere to somewhere with some flight transfers. For example: SFO->DFW DFW->JFK JFK->MIA MIA->ORD.
Unfortunately, after she received the tickets, she messed up the tickets and she forgot the order of the tickets.
Help Mary rearrange the tickets to make the tickets in correct order.
def merge_ordered_flights(ordered_flights)
while ordered_flights.size > 1
flights = ordered_flights.pop
ordered_flights.each do |a|
if a[0] == flights[-1]
a.insert(0, *flights)
break
elsif a[-1] == flights[0]
a.insert(-1, *flights)
break
end
end
end
return ordered_flights[0] #flatten
end
def order_flights(tickets)
ordered_flights = []
iter = 0
while true
#Get an arbitrary arrival, destination flight pair
arv, dest = tickets.shift
if arv == nil
break #Done if we are out of tickets
end
ordered_flights[iter] = []
ordered_flights[iter].push(arv, dest)
#And append follow-up destinations until we can't find one
#(It's the final destination, or the other tickets have already been sorted)
while true
arv = dest
dest = tickets.delete(dest)
if dest == nil
break #End of current chain
end
ordered_flights[iter].push(arv, dest)
end
iter += 1
end
#Now combine the ordered flight arrays into a single array
return merge_ordered_flights(ordered_flights)
end
def print_flights(case_num, ordered_flights)
flights = (0...ordered_flights.size).step(2).map {|i| ordered_flights[i] + '-' + ordered_flights[i+1] }.join ' '
puts "CASE ##{case_num}: #{flights}"
end
while not $stdin.eof?
num_cases = $stdin.readline.strip.to_i
(1..num_cases).each {
|num|
tickets = {}
num_flights = $stdin.readline.strip.to_i
(0...num_flights).each {
tickets[$stdin.readline.strip] = $stdin.readline.strip
}
ordered_flights = order_flights(tickets)
print_flights(num, ordered_flights)
}
end
Example input:
The first line contains the number of test cases T, after which T cases follow. For each case, it starts with an integer N. There are N flight tickets follow. Each of the next 2 lines contains the source and destination of a flight ticket.
2 1 SFO DFW 4 MIA ORD DFW JFK SFO DFW JFK MIA
Expected output:
Case #1: SFO-DFW Case #2: SFO-DFW DFW-JFK JFK-MIA MIA-ORD