Class: Graphunk::Graph
- Inherits:
-
Object
show all
- Defined in:
- lib/graphunk/graph.rb
Instance Method Summary
collapse
Constructor Details
#initialize(hash = {}) ⇒ Graph
Returns a new instance of Graph.
4
5
6
|
# File 'lib/graphunk/graph.rb', line 4
def initialize(hash = {})
@representation = hash
end
|
Instance Method Details
#add_vertex(name) ⇒ Object
22
23
24
25
26
27
28
|
# File 'lib/graphunk/graph.rb', line 22
def add_vertex(name)
unless vertex_exists?(name)
@representation[name] = []
else
raise ArgumentError, "Vertex already exists"
end
end
|
#add_vertices(*names) ⇒ Object
30
31
32
33
34
35
36
|
# File 'lib/graphunk/graph.rb', line 30
def add_vertices(*names)
if (names & vertices).count == 0
names.each { |name| add_vertex(name) }
else
raise ArgumentError, "One or more of the given vertices already exists"
end
end
|
#edge_exists?(first_vertex, second_vertex) ⇒ Boolean
67
68
69
|
# File 'lib/graphunk/graph.rb', line 67
def edge_exists?(first_vertex, second_vertex)
edges.include?(order_vertices(first_vertex, second_vertex))
end
|
#edges ⇒ Object
12
13
14
15
16
17
18
19
20
|
# File 'lib/graphunk/graph.rb', line 12
def edges
[].tap do |edge_constructor|
vertices.each do |vertex|
@representation[vertex].each do |neighbor|
edge_constructor << [vertex, neighbor]
end
end
end
end
|
#edges_on_vertex(name) ⇒ Object
59
60
61
62
63
64
65
|
# File 'lib/graphunk/graph.rb', line 59
def edges_on_vertex(name)
if vertex_exists?(name)
edges.select { |edge| edge.include?(name) }
else
raise ArgumentError, "That vertex does not exist in the graph"
end
end
|
#neighbors_of_vertex(name) ⇒ Object
49
50
51
52
53
54
55
56
57
|
# File 'lib/graphunk/graph.rb', line 49
def neighbors_of_vertex(name)
if vertex_exists?(name)
edges.select { |edge| edge.include? name }.map do |edge|
edge.first == name ? edge.last : edge.first
end
else
raise ArgumentError, "That vertex does not exist in the graph"
end
end
|
#remove_vertex(name) ⇒ Object
38
39
40
41
42
43
44
45
46
47
|
# File 'lib/graphunk/graph.rb', line 38
def remove_vertex(name)
if vertex_exists?(name)
edges.each do |edge|
remove_edge(edge.first, edge.last) if edge.include?(name)
end
@representation.delete(name)
else
raise ArgumentError, "That vertex does not exist in the graph"
end
end
|
#vertex_exists?(name) ⇒ Boolean
71
72
73
|
# File 'lib/graphunk/graph.rb', line 71
def vertex_exists?(name)
vertices.include?(name)
end
|
#vertices ⇒ Object
8
9
10
|
# File 'lib/graphunk/graph.rb', line 8
def vertices
@representation.keys
end
|