Class: Graph

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGraph

Returns a new instance of Graph.



5
6
7
# File 'lib/graph.rb', line 5

def initialize
  @vertices = []
end

Class Method Details

.from_file(filename) ⇒ Object



58
59
60
# File 'lib/graph.rb', line 58

def self.from_file(filename)
  self.from_hash(JSON.parse(File.read(filename)))
end

.from_hash(hash) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/graph.rb', line 46

def self.from_hash(hash)
  g = Graph.new
  hash['vertices'].each do |vertex|
    g.add_vertex(vertex)
  end

  hash['edges'].each do |from, to|
    g.add_edge(from, to)
  end
  return g
end

Instance Method Details

#add_edge(from, to) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/graph.rb', line 15

def add_edge(from, to)
  names = @vertices.map(&:name)
  #return false unless names.include?(from) && names.include?(to)
  @vertices[names.index(from)].add_child(to)
  @vertices[names.index(to)].add_parent(from)
  nil
end

#add_vertex(name) ⇒ Object



9
10
11
12
13
# File 'lib/graph.rb', line 9

def add_vertex(name)
  vertex = Vertex.new(name)
  @vertices << vertex
  vertex
end

#children_for(vertex) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/graph.rb', line 23

def children_for(vertex)
  names = @vertices.map(&:name)
  children_names = @vertices[names.index(vertex)].children
  children = children_names.collect do |child|
    @vertices[names.index(child)]
  end
  children
end

#get_vertex(name) ⇒ Object



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

def get_vertex(name)
  names = @vertices.map(&:name)
  @vertices[names.index(name)]
end

#parents_for(vertex) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/graph.rb', line 32

def parents_for(vertex)
  names = @vertices.map(&:name)
  parent_names = @vertices[names.index(vertex)].parents
  parents = parent_names.collect do |parent|
    @vertices[names.index(parent)]
  end
  parents
end