Class: PrettyAssociationInspect::Graph

Inherits:
Object
  • Object
show all
Defined in:
lib/pretty_association_inspect.rb

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Graph

Returns a new instance of Graph.



21
22
23
24
25
26
# File 'lib/pretty_association_inspect.rb', line 21

def initialize(data)
  @nodes = data.map do |node_id, edges|
    edges.map!{|edge| Edge.new(*edge)}
    Node.new(node_id, edges)
  end
end

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


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