Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'rubygems'
- require 'json'
- class Graph
- def initialize(data=nil)
- @graph = data || get_json_data
- @eccentricities = []
- end
- def get_json_data
- file = File.read("graph.json")
- JSON.parse(file)
- end
- def graph_nodes_count
- @graph.keys
- end
- def find_shortest_path(start, finish, travel_path=[])
- travel_path = Array.new(travel_path + start.split)
- return travel_path if (start == finish)
- return nil if !(@graph.include? start)
- shortest_path = nil
- for node in @graph[start] do
- if (!travel_path.include? node)
- if (new_path = find_shortest_path(node, finish, travel_path))
- shortest_path = new_path if (!shortest_path || new_path.length < shortest_path.length)
- end
- end
- end
- return shortest_path
- end
- def node_eccentricity(eccentricity, path)
- @eccentricities << eccentricity
- puts "ECCENTRICITY OF PATH: #{path} IS #{eccentricity}"
- end
- def get_radius
- radius = 9999
- for eccentricity in @eccentricities do
- if radius > eccentricity then
- radius = eccentricity
- end
- end
- radius
- end
- def get_diameter
- diameter = 0
- for eccentricity in @eccentricities do
- if diameter < eccentricity then
- diameter = eccentricity
- end
- end
- diameter
- end
- def show_all_eccentricities
- nodes = graph_nodes_count
- for start in nodes do
- max = 0
- max_path = []
- for finish in nodes do
- next if (start == finish)
- path = find_shortest_path(start, finish)
- eccentricity = path.length
- total = nodes.count + ((nodes.count - 1) * 2) + 2 # ":"
- subtotal = eccentricity + ((eccentricity - 1) * 2)
- tab = " " * (total - subtotal)
- eccentricity -= 1
- for point in path do
- (path.last == point) ? print("#{point}:#{tab}") : print("#{point}->") # Paths list
- end
- if (path && max < eccentricity) then
- max = eccentricity
- max_path = path
- end
- puts max
- end
- puts
- # puts max # and steps count
- node_eccentricity(max, max_path)
- end
- end
- end
- data = {'A'=> ['B', 'C'],
- 'B'=> ['A', 'C', 'D'],
- 'C'=> ['A', 'B', 'D', 'F'],
- 'D'=> ['B', 'C'],
- 'E'=> ['C', 'F'],
- 'F'=> ['C', 'E']
- }
- graph = Graph.new()
- graph.show_all_eccentricities
- p graph.get_radius
- p graph.get_diameter
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement