class GraphList

Attributes

edge_lists[RW]
type[RW]
weight_limit[RW]

Public Class Methods

new(args) click to toggle source
# File lib/graphify/graph_list.rb, line 3
def initialize(args)
  @type = args[:type]
  @weight_limit = args[:weight_limit]
  @edge_lists = {}
  if args.has_key?(:num_vertices)
    (0..args[:num_vertices] - 1).each do |num|
      @edge_lists[num] = {}
    end
    initialize_edges(args[:num_vertices], args[:num_edges])
  else
    @edge_lists = args[:edge_lists]
  end
end

Public Instance Methods

edges() click to toggle source
# File lib/graphify/graph_list.rb, line 38
def edges
  result = []
  @edge_lists.keys.each do |k|
    @edge_lists[k].keys.each do |s_k|
      next if @type == 'undirected' && s_k > k
      result << [k, s_k]
    end
  end
  result
end
edges_with_weights() click to toggle source
# File lib/graphify/graph_list.rb, line 49
def edges_with_weights
  result = []
  @edge_lists.keys.each do |k|
    @edge_lists[k].keys.each do |s_k|
      next if @type == 'undirected' && s_k > k
      result << [k, s_k, @edge_lists[k][s_k]]
    end
  end
  result
end
get_edge_weight(to, from) click to toggle source
# File lib/graphify/graph_list.rb, line 26
def get_edge_weight(to, from)
  @edge_lists[to][from]
end
get_in_edges(vertex) click to toggle source
# File lib/graphify/graph_list.rb, line 22
def get_in_edges(vertex)
  @edge_lists.reduce([]) { |memo, (key, value)| value.has_key?(vertex) ? memo << key : memo }
end
get_out_edges(vertex) click to toggle source
# File lib/graphify/graph_list.rb, line 18
def get_out_edges(vertex)
  @edge_lists[vertex].keys
end
vertices() click to toggle source
# File lib/graphify/graph_list.rb, line 30
def vertices
  result = []
  (0..@edge_lists.keys.size - 1).each do |vertex|
    result << vertex
  end
  result
end

Private Instance Methods

add_edge_helper(to, from, counter) click to toggle source
# File lib/graphify/graph_list.rb, line 72
def add_edge_helper(to, from, counter)
  return counter if @edge_lists[from].has_key?(to)
  @edge_lists[from][to] = generate_edge_weight
  @edge_lists[to][from] = @edge_lists[from][to] if @type == 'undirected'
  counter + 1
end
generate_edge_weight() click to toggle source
# File lib/graphify/graph_list.rb, line 79
def generate_edge_weight
  if @weight_limit == 0
    1
  else
    rand(@weight_limit)
  end
end
initialize_edges(num_vertices, num_edges) click to toggle source
# File lib/graphify/graph_list.rb, line 62
def initialize_edges(num_vertices, num_edges)
  counter = 0
  while counter < num_edges
    forward = rand(num_vertices)
    to = rand(num_vertices)
    next if forward == to
    counter = add_edge_helper(to, forward, counter)
  end
end