Created
August 19, 2014 19:01
-
-
Save mh-github/5ed202b007d3f0cf3b2e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/ruby | |
| require './dijkstra' | |
| def haversine (lat1, lon1, lat2, lon2) | |
| r = 6371 # earth radius, km | |
| degToRadConvFac = Math::PI / 180 | |
| p1 = lat1 * degToRadConvFac | |
| p2 = lat2 * degToRadConvFac | |
| delP = (lat2 - lat1) * degToRadConvFac | |
| delL = (lon2 - lon1) * degToRadConvFac | |
| a = Math.sin(delP/2) * Math.sin(delP/2) + Math.cos(p1) * Math.cos(p2) * Math.sin(delL/2) * Math.sin(delL/2) | |
| c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)) | |
| d = r * c | |
| end | |
| # Open airports.dat | |
| # On each line, airport IATA code = 5th value, latitude = 7th value, longitude = 8th value | |
| # Populate airport IATA code, latitude, longitude in a data structure (hash, key=code, value=list[latitude, longitude]) | |
| h = Hash.new {|hash, key| hash[key] = []} | |
| File.open("airports.dat", "r") do |file| | |
| file.each_line do |line| | |
| fields = line.split(/,/) | |
| if fields[4] != '""' | |
| h[fields[4].delete('"')] << fields[6] << fields[7] | |
| end | |
| end | |
| end | |
| # Initialize a graph | |
| graph = Graph.new | |
| # Open routes.dat | |
| # On each line, orig airport IATA code = 3rd value, dest airport IATA code = 5th value | |
| # Make Graph vertices from the IATA codes (if they are already not vertices) | |
| # Calculate distance | |
| # -- Get orig airport latitude & longitude, dest airport latitude & longitude | |
| # -- and pass them to haversine method to get distance | |
| # Connect the airports with distance as graph Edges | |
| File.open("routes.dat", "r") do |file| | |
| file.each_line do |line| | |
| fields = line.split(/,/) | |
| orig = fields[2] | |
| dest = fields[4] | |
| if h.has_key?orig and h.has_key?dest | |
| graph.push orig if ! (graph.include?orig) | |
| graph.push dest if ! (graph.include?dest) | |
| dist = haversine h[orig][0].to_f, h[orig][1].to_f, h[dest][0].to_f, h[dest][1].to_f | |
| graph.connect orig, dest, dist.to_i if dist > 0 | |
| end | |
| end | |
| end | |
| # Take an airports pair as user input | |
| # Print the shortest path and distance | |
| p "Enter from-city" | |
| a = STDIN.gets.chomp | |
| p "Enter to-city" | |
| b = STDIN.gets.chomp | |
| p graph.dijkstra(a, b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment