Class: Graph

Inherits:
Object
  • Object
show all
Includes:
BreadthFirstSearch, DepthFirstSearch
Defined in:
lib/honey_mushroom/graph.rb

Direct Known Subclasses

DirectedGraph, UndirectedGraph

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from BreadthFirstSearch

#breadth_first_search_include?

Methods included from DepthFirstSearch

#depth_first_search_include?

Constructor Details

#initializeGraph

Returns a new instance of Graph.



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

def initialize
  @nodes = {}
end

Instance Attribute Details

#nodesObject

Returns the value of attribute nodes.



7
8
9
# File 'lib/honey_mushroom/graph.rb', line 7

def nodes
  @nodes
end

Instance Method Details

#add_edge(node_id, edge) ⇒ Object



33
34
35
# File 'lib/honey_mushroom/graph.rb', line 33

def add_edge(node_id, edge)
  @nodes[node_id].edges << edge
end

#add_node(value, edges = []) ⇒ Object



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

def add_node(value, edges=[])
  node = Node.new({value: value, edges: edges})
  @nodes[node.id] = node
  self
end

#adjacent?(node_id, edge) ⇒ Boolean

Returns:

  • (Boolean)


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

def adjacent?(node_id, edge)
  @nodes[node_id].edges.include?(edge)
end

#delete_edge(node_id, edge_id) ⇒ Object



37
38
39
# File 'lib/honey_mushroom/graph.rb', line 37

def delete_edge(node_id, edge_id)
  @nodes[node_id].edges.delete(edge_id)
end

#delete_node(node_id) ⇒ Object



21
22
23
# File 'lib/honey_mushroom/graph.rb', line 21

def delete_node(node_id)
  @nodes.delete(node_id)
end

#get_id_from_value(value) ⇒ Object



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

def get_id_from_value(value)
  #TODO
  #find a fast way to get id from value
  #returns an array of all node ids with a given value
end

#get_node_value(node_id) ⇒ Object



25
26
27
# File 'lib/honey_mushroom/graph.rb', line 25

def get_node_value(node_id)
  @node[node_id].value
end

#neighbors(node_id) ⇒ Object



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

def neighbors(node_id)
  @nodes[node_id].edges
end

#set_node_value(node_id, value) ⇒ Object



29
30
31
# File 'lib/honey_mushroom/graph.rb', line 29

def set_node_value(node_id, value)
  @nodes[node_id].value = value
end

#to_sObject

FIXIT: to_s broken for undirected graph



50
51
52
53
54
55
56
# File 'lib/honey_mushroom/graph.rb', line 50

def to_s
  s = ""
  @nodes.each do |node_id, node|
    s += "#{node_id} (#{node.value}) => #{node.edges} \n"
  end
  return s
end