Class: PrettyAssociationInspect::Graph
- Inherits:
-
Object
- Object
- PrettyAssociationInspect::Graph
- Defined in:
- lib/pretty_association_inspect.rb
Instance Method Summary collapse
-
#initialize(data) ⇒ Graph
constructor
A new instance of Graph.
- #minimum_route(start_id, goal_id, max_cost) ⇒ Object
- #print_route(route) ⇒ Object
- #search_by_dikstra(start_id, goal_id, max_cost) ⇒ Object
Constructor Details
Instance Method Details
#minimum_route(start_id, goal_id, max_cost) ⇒ Object
43 44 45 46 47 48 49 50 51 |
# File 'lib/pretty_association_inspect.rb', line 43 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) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/pretty_association_inspect.rb', line 28 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) ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/pretty_association_inspect.rb', line 53 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 |