Class: MGraph::Graph

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

Instance Method Summary collapse

Constructor Details

#initialize(graph_store = VertexEdgeTable.new) ⇒ Graph

Returns a new instance of Graph.



8
9
10
# File 'lib/mgraph/graph.rb', line 8

def initialize graph_store = VertexEdgeTable.new
  @graph_store = graph_store
end

Instance Method Details

#add_edge(v1, v2) ⇒ Object



12
13
14
15
16
# File 'lib/mgraph/graph.rb', line 12

def add_edge v1, v2
  edge = Edge.new v1, v2
  @graph_store.add_edge edge
  edge
end

#breadth_first_traverse(starting_vertex) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/mgraph/graph.rb', line 18

def breadth_first_traverse starting_vertex
  return enum_for(:breadth_first_traverse, starting_vertex) unless block_given?

  queue = [starting_vertex, *neighbors(starting_vertex)]
  visited = []
  while vertex = queue.shift
    yield vertex
    visited << vertex
    queue += neighbors(vertex).to_a - visited
    queue = queue.uniq
  end
end

#each_vertexObject



31
32
33
34
# File 'lib/mgraph/graph.rb', line 31

def each_vertex
  return vertices.each unless block_given?
  vertices.each { |vertex| yield vertex }
end

#edgesObject



36
37
38
# File 'lib/mgraph/graph.rb', line 36

def edges
  @graph_store.edges
end

#has_edge?(v1, v2) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
43
# File 'lib/mgraph/graph.rb', line 40

def has_edge? v1, v2
  edge = Edge.new v1, v2
  edges.include? edge
end

#has_vertex?(vertex) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/mgraph/graph.rb', line 45

def has_vertex? vertex
  vertices.include? vertex
end

#neighbors(vertex) ⇒ Object



49
50
51
# File 'lib/mgraph/graph.rb', line 49

def neighbors vertex
  @graph_store.neighbors vertex
end

#verticesObject



53
54
55
# File 'lib/mgraph/graph.rb', line 53

def vertices
  @graph_store.vertices
end