class PrettyAssociationInspect::Graph
Public Class Methods
new(data)
click to toggle source
# File lib/pretty_association_inspect.rb, line 20 def initialize(data) @nodes = data.map do |node_id, edges| edges.map!{|edge| Edge.new(*edge)} Node.new(node_id, edges) end end
Public Instance Methods
minimum_route(start_id, goal_id, max_cost)
click to toggle source
# File lib/pretty_association_inspect.rb, line 42 def minimum_route(start_id, goal_id, max_cost) search_by_dikstra(start_id, goal_id, max_cost) passage = @nodes.find { |node| node.id == goal_id } route = [passage] while passage = @nodes.find { |node| node.id == passage.from } route << passage end route end
print_route(route)
click to toggle source
# File lib/pretty_association_inspect.rb, line 27 def print_route(route) return false if route[0].cost.nil? route_arr = route.map{|node| node.id} start_name = route_arr.pop.to_s.camelize route_arr.reverse! h = Hash.new h[route_arr.first] = {} if route_arr.count == 1 h[route_arr.first] = route_arr.second if route_arr.count == 2 h[route_arr.first] = {route_arr.second => route_arr.third} if route_arr.count == 3 h[route_arr.first] = {route_arr.second => {route_arr.third => route_arr.fourth}} if route_arr.count == 4 route_str = "#{start_name}.joins(#{h.to_s}).last." + route_arr.join(".").gsub("s.", "s.last.") ap route_str return route_str end
search_by_dikstra(start_id, goal_id, max_cost)
click to toggle source
# File lib/pretty_association_inspect.rb, line 52 def search_by_dikstra(start_id, goal_id, max_cost) @nodes.each do |node| node.cost = node.id == start_id ? 0 : nil node.done = false node.from = nil end loop do next_node = nil @nodes.each do |node| next if node.done || node.cost.nil? next_node = node if next_node.nil? || node.cost < next_node.cost end break if next_node.nil? next_node.done = true next_node.edges.each do |edge| reachble_node = @nodes.find { |node| node.id == edge.node_id } reachble_cost = next_node.cost + edge.cost next if reachble_node.nil? next if reachble_cost > max_cost if reachble_node.cost.nil? || reachble_cost < reachble_node.cost reachble_node.cost = reachble_cost reachble_node.from = next_node.id end end end end