I've found a great new site for interesting and challenging programming exercises called TalentBuddy. Today I completed a fairly straight forward algorithm to reconstruct a travel itinerary from a pair of parallel arrays containing all the history departures and destinations. One of the neat things about TalentBuddy is that they expose your work to fairly large data sets (around 10,000 elements) and have a two second timeout, so implementations must be efficient.
My implementation begins by mapping the parallel arrays to a hash of destinations and departures. Then we calculate the first departure by getting the intersection of the two original arrays. Then a loop begins iterating through all destinations, retracing the history. This is made easy by the fact that no destination is visited twice. Finally, we have to handle the final case where the loop terminates when no additional destinations are found, printing the final destination. As always, full source is on GitHub
class PlaneTickets def get_journey(departure_ids, destination_ids) destination_for = map_departures_to_destinations(departure_ids, destination_ids) next_departure = (departure_ids - destination_ids).first while next_departure puts next_departure last_departure = next_departure next_departure = destination_for[next_departure] end puts destination_for[last_departure] end end
No comments:
Post a Comment