lib/rgl/adjacency.rb in rgl-0.2.3 vs lib/rgl/adjacency.rb in rgl-0.3.0
- old
+ new
@@ -1,8 +1,8 @@
# adjacency.rb
#
-# $Id: adjacency.rb,v 1.7 2005/03/30 21:25:34 monora Exp $
+# $Id: adjacency.rb,v 1.11 2008/03/02 13:45:43 monora Exp $
#
# The DirectedAdjacencyGraph class implements a generalized adjacency list
# graph structure. An AdjacencyGraph is basically a two-dimensional structure
# (ie, a list of lists). Each element of the first dimension represents a
# vertex. Each of the vertices contains a one-dimensional structure that is
@@ -33,25 +33,39 @@
end
# Returns a new empty DirectedAdjacencyGraph which has as its edgelist
# class the given class. The default edgelist class is Set, to ensure
# set semantics for edges and vertices.
-
- def initialize (edgelist_class = Set)
+ #
+ # If other graphs are passed as parameters their vertices and edges are
+ # added to the new graph.
+ def initialize (edgelist_class = Set, *other_graphs)
@edgelist_class = edgelist_class
@vertice_dict = Hash.new
+ other_graphs.each do |g|
+ g.each_vertex {|v| add_vertex v}
+ g.each_edge {|v,w| add_edge v,w}
+ end
end
+ # Copy internal vertice_dict
+ def initialize_copy(orig)
+ @vertice_dict = orig.instance_eval{@vertice_dict}.dup
+ @vertice_dict.keys.each do |v|
+ @vertice_dict[v] = @vertice_dict[v].dup
+ end
+ end
+
# Iterator for the keys of the vertice list hash.
def each_vertex (&b)
@vertice_dict.each_key(&b)
end
def each_adjacent (v, &b) # :nodoc:
- adjacency_list = @vertice_dict[v] or
- raise NoVertexError, "No vertex #{v}."
+ adjacency_list = (@vertice_dict[v] or
+ raise NoVertexError, "No vertex #{v}.")
adjacency_list.each(&b)
end
# Returns true.
@@ -107,10 +121,19 @@
def remove_edge (u, v)
@vertice_dict[u].delete(v) unless @vertice_dict[u].nil?
end
+ # Converts the adjacency list of each vertex to be of type _klass_. The
+ # class is expected to have a new contructor which accepts an enumerable as
+ # parameter.
+ def edgelist_class=(klass)
+ @vertice_dict.keys.each do |v|
+ @vertice_dict[v] = klass.new @vertice_dict[v].to_a
+ end
+ end
+
protected
def basic_add_edge (u, v)
@vertice_dict[u].add(v)
end
@@ -173,12 +196,10 @@
#
# If the graph is undirected, the result is self.
def to_undirected
return self unless directed?
- result = AdjacencyGraph.new
- each_edge { |u,v| result.add_edge(u, v) }
- result
+ AdjacencyGraph.new(Set, self)
end
end # module Graph
end # module RGL