Class: Graphos::Weighted::Node

Inherits:
Object
  • Object
show all
Defined in:
lib/graphos/weighted/node.rb

Overview

This class represents a node in a weighted graph

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(index) ⇒ Node

Returns a new instance of Node.



9
10
11
12
13
# File 'lib/graphos/weighted/node.rb', line 9

def initialize index
  @index = index
  @edges = []
  @edge_count = 0
end

Instance Attribute Details

#indexObject (readonly)

Returns the value of attribute index.



8
9
10
# File 'lib/graphos/weighted/node.rb', line 8

def index
  @index
end

Instance Method Details

#add_edge(to, weight) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/graphos/weighted/node.rb', line 20

def add_edge to, weight
  # Does a O(n) check deleting existing edges
  current_idx = @edges.index{|n| n.to == to}
  if current_idx
    @edges[current_idx] = Edge.new(self,to,weight)
  else
    @edges << Edge.new(self, to, weight)
    @edge_count += 1
  end
end

#degreeObject



31
32
33
# File 'lib/graphos/weighted/node.rb', line 31

def degree
  edges.inject(0){|sum,e| sum+e.weight }
end

#edge(to) ⇒ Object



43
44
45
# File 'lib/graphos/weighted/node.rb', line 43

def edge to
  edges.lazy.select{|e| e.to.index == to}.first
end

#edgesObject



15
16
17
18
# File 'lib/graphos/weighted/node.rb', line 15

def edges
  return [] if @edge_count == 0
  @edges[0..@edge_count-1]
end

#neighbor_of?(index) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/graphos/weighted/node.rb', line 35

def neighbor_of? index
  edges.any? {|node| node.to.index == index }
end

#neighborsObject



39
40
41
# File 'lib/graphos/weighted/node.rb', line 39

def neighbors
  edges.map{|edge| edge.to}
end