X-Git-Url: https://git.njae.me.uk/?a=blobdiff_plain;f=lib%2Fgraph.njae%2Fgraph.rb;h=acfc9e07e998ee3843aa19e990f7670d38a8bcce;hb=e3fe1f33fea019106289edfae4e7a32f3ba3e03b;hp=1da5297d1f74861b24ce417dc2ac6c0ff3181111;hpb=c34def40508c16cfc815fa02c8743d071491af7b;p=graph.njae.git diff --git a/lib/graph.njae/graph.rb b/lib/graph.njae/graph.rb index 1da5297..acfc9e0 100644 --- a/lib/graph.njae/graph.rb +++ b/lib/graph.njae/graph.rb @@ -7,8 +7,8 @@ module GraphNjae # A container for all the parts of a graph. The graph can have arbitrary attributes, # treated as method names. class Graph < OpenStruct - def initialize - super + def initialize(values = {}) + super(values) self.edges = Array.new self.vertices = Array.new self @@ -16,12 +16,47 @@ module GraphNjae # Add a Vertex or Edge to the graph. def <<(other) - if other.class == Vertex + if other.class.ancestors.include? Vertex self.vertices << other - elsif + elsif other.class.ancestors.include? Edge self.edges << other end self end - end + + # Connects two vertices, creating and storing a new edge + # Also adds the vertices, unless they're already in the graph + def connect(vertex1, vertex2) + self.vertices << vertex1 unless self.vertices.include? vertex1 + self.vertices << vertex2 unless self.vertices.include? vertex2 + edge = Edge.new + self.edges << edge + edge << vertex1 << vertex2 + end + + # Form a product graph of this graph and the other. + # Return the new graph. + def product(other) + product_graph = Graph.new + self.vertices.each do |v1| + other.vertices.each do |v2| + product_graph << Vertex.new({:g1_vertex => v1, :g2_vertex => v2}) + end + end + self.edges.each do |e1| + e1_vertices = e1.vertices + other.edges.each do |e2| + e2_vertices = e2.vertices + source = product_graph.vertices.find {|v| v.g1_vertex == e1_vertices[0] and v.g2_vertex == e2_vertices[0]} + destination = product_graph.vertices.find {|v| v.g1_vertex == e1_vertices[1] and v.g2_vertex == e2_vertices[1]} + product_graph.connect source, destination + source = product_graph.vertices.find {|v| v.g1_vertex == e1_vertices[0] and v.g2_vertex == e2_vertices[1]} + destination = product_graph.vertices.find {|v| v.g1_vertex == e1_vertices[1] and v.g2_vertex == e2_vertices[0]} + product_graph.connect source, destination + end + end + product_graph + end + + end # class end