Reputation: 109
I am writing a class that will sort an array of airport codes in a way that would simulate an aircrafts flight path between multiple cities.
For example: Given an array [['LAX', 'BWI'], ['BOS', 'SEA'], ['HNL', 'LAX'], ['SEA', 'HNL']]
where the first index of each sub array is the
departing airport and the second is the destination airport, the sort_flight_path
method would return [['BOS', 'SEA'], ['SEA', 'HNL'], ['HNL', 'LAX'], ['LAX', 'BWI']]
.
I have a method that finds the start point as an index value, and I have the following method that returns a new sorted array.
def sort_flight_path
flight_path = [] << @list[@start_point]
start = @start_point
until flight_path.size == @list.size
@list.each do |i|
if @list[start][1] == i[0]
flight_path << i
start = @list.index(i)
end
end
end
flight_path
end
As I am becoming more comfortable with Ruby, I want to find a more "Ruby like" way to accomplish this.
Upvotes: 0
Views: 71
Reputation: 110675
I agree with @Karoly that it makes sense to convert the list to a hash as the first step. Once done, there are many ways to build the flight path. Here's how it could be done using recursion:
list = [['LAX', 'BWI'], ['BOS', 'SEA'], ['HNL', 'LAX'], ['SEA', 'HNL']]
h = list.to_h # Use Hash[list] for versions < 2.0
#=> {"LAX"=>"BWI", "BOS"=>"SEA", "HNL"=>"LAX", "SEA"=>"HNL"}
def route(start_city, h)
return start_city if h.empty?
[start_city, *route(h.delete(start_city), h)]
end
The determination of the city where the flight began was addressed in your previous question. In your example it is 'BOS', so we compute:
route('BOS',h)
#=> ["BOS", "SEA", "HNL", "LAX", "BWI"]
In effect, we ask "where do we go from Boston?" and get the answer "Seattle". We then have the same question as before, except we are starting from Seattle, and the list no longer has the "Bos->Sea" leg.
Upvotes: 1
Reputation: 96266
I think by far the best thing you can do is to convert the list to an array, so that lookup becomes trivial:
Hash[list] # => {"LAX"=>"BWI", "BOS"=>"SEA", "HNL"=>"LAX", "SEA"=>"HNL"}
Working example:
list = [['LAX', 'BWI'], ['BOS', 'SEA'], ['HNL', 'LAX'], ['SEA', 'HNL']]
start_point = 1
airport = list[start_point][0]
flight_path = []
h = Hash[list]
h.size.times do
flight_path << [airport, h[airport]]
airport = h[airport]
end
Upvotes: 2