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, size = 0) ⇒ Node

Returns a new instance of Node.



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

def initialize index, size=0
  @index = index
  @edges = Array.new(size||0)
  @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
30
31
32
33
34
# 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
    edge = Edge.new(self, to, weight)
    if(@edges.size > @edge_count)
      @edges[@edge_count] = edge
    else
      @edges << edge
    end
    @edge_count += 1
  end
end

#degreeObject



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

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

#edge(to) ⇒ Object



48
49
50
# File 'lib/graphos/weighted/node.rb', line 48

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)


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

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

#neighborsObject



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

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