Skip to content

Instantly share code, notes, and snippets.

@lostmarinero
Created January 14, 2014 18:52
Show Gist options
  • Save lostmarinero/8423633 to your computer and use it in GitHub Desktop.
Save lostmarinero/8423633 to your computer and use it in GitHub Desktop.
This is a coding challenge focused on finding all the routes for a network of flights. I added Portland as a city to make it a little more complex. The original challenge: Express the following table as a static structure, and write a function, find_routes(source, destination) that efficiently outputs all possible routes.
# Flights, Ruby
#
# Express the following table as a static structure,
# and write a function, find_routes(source, destination) that
# efficiently outputs all possible routes.
#
# Source | Dest
# ~~~~~~ ~~~~
# Seattle | LA
# LA | Florida
# LA | Maine
# Florida | Seattle
# Seattle | Florida
# LA | Portland
# Portland| Florida
# puts find_routes('Seattle', 'Florida') == ['Seattle -> Florida', 'Seattle -> LA -> Florida'])
class City
attr_reader :name, :destinations
def initialize(name)
@name = name #String
@destinations = [] #Array<City>
end
def add_destinations(cities)
cities.each { |city| self.destinations << city }
end
end
class Route
attr_reader :all_cities
def initialize(routes)
city_list = find_all_cities(routes)
@all_cities = create_cities(city_list)
create_destinations(@all_cities, routes)
end
def find_all_cities(routes)
cities = routes.keys
cities << routes.values
cities.flatten.compact.uniq
end
def create_cities(city_list)
# Returns Array<City>>
city_list.map! { |city| City.new(city) }
end
def create_destinations(cities, routes)
# Returns Array<City>>
cities.each do |origin_city|
if routes.has_key?(origin_city.name)
destinations = cities.select {|destination_city| routes[origin_city.name].include?(destination_city.name) }
origin_city.add_destinations(destinations)
end
end
end
def find_routes(current_city, destination, route = [], valid_routes = [])
# Returns Array<Array<City>>, Returns Array of Array of Cities
if current_city == destination
valid_routes << route + [current_city]
return valid_routes
end
current_city.destinations.each do |next_city|
find_routes(next_city, destination, route + [current_city], valid_routes)
end
valid_routes
end
def find_city(query)
self.all_cities.find {| city| city.name == query }
end
def find_routes_string(string_origin, string_destination)
origin_city, destination_city = find_city(string_origin), find_city(string_destination)
final_routes = find_routes(origin_city, destination_city)
final_routes.each {|f_route| f_route.map!(&:name) }
end
end
all_routes = { "LA" => ["Florida", "Maine"], "Seattle" => ["LA", "Florida", "Portland"], "Florida" => ["Seattle"], "Portland" => ["Florida"]}
route = Route.new(all_routes)
p route.find_routes_string('Seattle', 'Florida')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment