class Graph
Represents any weighted, directed graph.
Author: Johnny Lee Othon
Public Class Methods
new()
click to toggle source
# File lib/usearchtree/graph.rb, line 6 def initialize @nodes = Array.new @next_id = 0 end
Public Instance Methods
add_edge(i, j, cost)
click to toggle source
Adds an edge from node i to node j. Where i and j can be an index or a name.
# File lib/usearchtree/graph.rb, line 40 def add_edge i, j, cost self.node(i).add_edge self.node(j), cost end
add_node(name=nil)
click to toggle source
Adds a node to the graph and optionally sets a name.
# File lib/usearchtree/graph.rb, line 34 def add_node name=nil @nodes << Node.new(self.next_id, name) end
cost(i, j)
click to toggle source
Gets the cost from node at i to node at j.
# File lib/usearchtree/graph.rb, line 55 def cost i, j nodeI = (i.kind_of? Node) ? i : self.node(i) nodeJ = (j.kind_of? Node) ? j : self.node(j) nodeI.cost(nodeJ) end
label_node(i, name)
click to toggle source
Labels a single node with index i. Fails if the node does not exist.
# File lib/usearchtree/graph.rb, line 45 def label_node i, name @nodes[i].name = name end
length()
click to toggle source
Gets the number of nodes in the graph
# File lib/usearchtree/graph.rb, line 50 def length @nodes.length end
next_id()
click to toggle source
Gets and increases the next id.
# File lib/usearchtree/graph.rb, line 62 def next_id id = @next_id @next_id += 1 id end
node(key)
click to toggle source
# File lib/usearchtree/graph.rb, line 25 def node key if key.kind_of? Integer @nodes[key] else @nodes.find{|n| n.name == key} end end
to_adjacency_lists()
click to toggle source
Returns the graph as a list of adjacencies
# File lib/usearchtree/graph.rb, line 17 def to_adjacency_lists if @nodes.empty? "Empty graph" else @nodes.collect{|node| node.to_adjacency_list}.join("\n") end end
to_s()
click to toggle source
Returns the list of nodes
# File lib/usearchtree/graph.rb, line 12 def to_s @nodes.to_s end