class AdjacencyMatrix::Matrix

Attributes

graph[R]
matrix[R]
nodes[R]

Public Class Methods

new(nodes, graph, matrix = nil) click to toggle source
# 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

Public Instance Methods

==(other) click to toggle source

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

# File lib/adjacency_matrix.rb, line 53
def ==(other)
  matrix == other.matrix
end
clone() click to toggle source

Copy an existing matrix

# File lib/adjacency_matrix.rb, line 48
def clone
  Matrix.new(nodes, graph, Marshal.load(Marshal.dump(matrix)))
end
get(from, to) click to toggle source

Get the distance between the two given nodes

# 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) click to toggle source

Set the distance between the two given nodes

# 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_s() click to toggle source
# 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

Private Instance Methods

get_distance(from, to) click to toggle source
# File lib/adjacency_matrix.rb, line 68
def get_distance(from, to)
  return 0 if from == to
  return 999999 if !graph.contains_edge?(from, to)
  return graph.get_edge_weight(from, to)
end
init_matrix() click to toggle source
# File lib/adjacency_matrix.rb, line 59
def init_matrix
  nodes.each_with_index do |from, fi|
    matrix[fi] = []
    nodes.each_with_index do |to, ti|
      matrix[fi] << get_distance(from, to)
    end
  end
end