Class: Newral::Graphs::Path

Inherits:
Object
  • Object
show all
Defined in:
lib/newral/graphs/path.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(edges: [], allow_circular_paths: true) ⇒ Path

Returns a new instance of Path.



10
11
12
13
# File 'lib/newral/graphs/path.rb', line 10

def initialize( edges:[], allow_circular_paths: true )
  @edges = edges.dup
  @allow_circular_paths = allow_circular_paths
end

Instance Attribute Details

#edgesObject (readonly)

Returns the value of attribute edges.



9
10
11
# File 'lib/newral/graphs/path.rb', line 9

def edges
  @edges
end

Instance Method Details

#add_edge(edge) ⇒ Object



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

def add_edge( edge )
  last_edge = @edges.last 
  raise Errors::CanOnlyConnectToLastEdge,[last_edge,edge] unless  @edges.empty? || last_edge.end_node == edge.start_node 
  raise Errors::CircularPath unless @allow_circular_paths && !@edges.index{|edge1| edge1.start_node == edge.end_node || edge1.end_node == edge.end_node }
  @edges << edge   
  self  
end

#costObject



27
28
29
# File 'lib/newral/graphs/path.rb', line 27

def cost 
  @edges.inject(0){ |value,edge| value+edge.cost }
end

#end_nodeObject



37
38
39
# File 'lib/newral/graphs/path.rb', line 37

def end_node
  @edges.last.end_node
end

#lengthObject



23
24
25
# File 'lib/newral/graphs/path.rb', line 23

def length 
  @edges.length 
end

#start_nodeObject



32
33
34
# File 'lib/newral/graphs/path.rb', line 32

def start_node
  @edges.first.start_node
end

#to_sObject



41
42
43
# File 'lib/newral/graphs/path.rb', line 41

def to_s
  @edges.join(', ')
end