diff --git a/lib/abstract_graph/graph.rb b/lib/abstract_graph/graph.rb index f98a3df..c23397c 100644 --- a/lib/abstract_graph/graph.rb +++ b/lib/abstract_graph/graph.rb @@ -25,3 +25,4 @@ class Graph require "abstract_graph/graph/delete_edge" require "abstract_graph/graph/change_vertex_name" require "abstract_graph/graph/change_edge_name" +require "abstract_graph/graph/is_adjacent" diff --git a/lib/abstract_graph/graph/is_adjacent.rb b/lib/abstract_graph/graph/is_adjacent.rb new file mode 100644 index 0000000..088d26a --- /dev/null +++ b/lib/abstract_graph/graph/is_adjacent.rb @@ -0,0 +1,20 @@ +# required in "abstract_graph/graph" + +module AbstractGraph + class Graph + + # returns whether or not v1 and v2 are joined by an edge + # p: String v1, v2 represents the names of the vertices + def is_adjacent?( v1, v2 ) + vertices = [v1, v2].sort! + + ( @edges.each_value.find do |e| + vertices == e.vertices.map do |v| + v.name + end.sort + end && true ) || false + + end + + end +end diff --git a/spec/abstract_graph/graph/is_adjacent_spec.rb b/spec/abstract_graph/graph/is_adjacent_spec.rb new file mode 100644 index 0000000..979127f --- /dev/null +++ b/spec/abstract_graph/graph/is_adjacent_spec.rb @@ -0,0 +1,38 @@ +require 'spec_helper' + +module AbstractGraph + module Composition + describe Graph do + + before :all do + @vertex1 = "Vertex1" + @vertex2 = "Vertex2" + @vertex3 = "Vertex3" + @edge1 = "Edge1" + @edge2 = "Edge2" + end + + before :each do + @graph = Graph.new + @graph.add_vertex @vertex1 + @graph.add_vertex @vertex2 + @graph.add_vertex @vertex3 + @graph.add_edge @edge1, @vertex1, @vertex2 + @graph.add_edge @edge2, @vertex2, @vertex3 + end + + describe "#is_adjacent?(String,String)" do + + it "returns true if two vertices are joined with an edge" do + @graph.is_adjacent?( @vertex1, @vertex2 ).should be_true + end + + it "returns false if two vertices are not joined with an edge" do + @graph.is_adjacent?( @vertex1, @vertex3 ).should be_false + end + + end + + end + end +end