Class: AdjacencyMatrix::Matrix

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(nodes, graph, matrix = nil) ⇒ Matrix

Returns a new instance of Matrix.



10
11
12
13
14
15
16
17
18
19
# File 'lib/adjacency_matrix.rb', line 10

def initialize(nodes, graph, matrix = nil)
  @nodes = nodes
  @graph = graph
  if matrix.nil?
    @matrix = []
    init_matrix
  else
    @matrix = matrix
  end
end

Instance Attribute Details

#graphObject (readonly)

Returns the value of attribute graph.



8
9
10
# File 'lib/adjacency_matrix.rb', line 8

def graph
  @graph
end

#matrixObject (readonly)

Returns the value of attribute matrix.



8
9
10
# File 'lib/adjacency_matrix.rb', line 8

def matrix
  @matrix
end

#nodesObject (readonly)

Returns the value of attribute nodes.



8
9
10
# File 'lib/adjacency_matrix.rb', line 8

def nodes
  @nodes
end

Instance Method Details

#==(other) ⇒ Object

Check for equality, i.e. if all values are the same



53
54
55
# File 'lib/adjacency_matrix.rb', line 53

def ==(other)
  matrix == other.matrix
end

#cloneObject

Copy an existing matrix



48
49
50
# File 'lib/adjacency_matrix.rb', line 48

def clone
  Matrix.new(nodes, graph, Marshal.load(Marshal.dump(matrix)))
end

#get(from, to) ⇒ Object

Get the distance between the two given nodes



22
23
24
25
26
# File 'lib/adjacency_matrix.rb', line 22

def get(from, to)
  fi = nodes.index(from)
  ti = nodes.index(to)
  matrix[fi][ti]
end

#set(from, to, value) ⇒ Object

Set the distance between the two given nodes



29
30
31
32
33
# File 'lib/adjacency_matrix.rb', line 29

def set(from, to, value)
  fi = nodes.index(from)
  ti = nodes.index(to)
  matrix[fi][ti] = value
end

#to_sObject



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/adjacency_matrix.rb', line 35

def to_s
  str = " \t" + nodes.join("\t") + "\n"
  nodes.each do |from|
    str += from
    nodes.each do |to|
      str += "\t#{get(from, to)}"
    end
    str += "\n"
  end
  return str
end