class Graphunk::Graph
Public Class Methods
new(hash = {})
click to toggle source
# File lib/graphunk/graph.rb, line 4 def initialize(hash = {}) @representation = hash end
Public Instance Methods
add_vertex(name)
click to toggle source
# File lib/graphunk/graph.rb, line 22 def add_vertex(name) unless vertex_exists?(name) @representation[name] = [] else raise ArgumentError, "Vertex already exists" end end
add_vertices(*names)
click to toggle source
# File lib/graphunk/graph.rb, line 30 def add_vertices(*names) if (names & vertices).count == 0 names.each { |name| add_vertex(name) } else raise ArgumentError, "One or more of the given vertices already exists" end end
edge_exists?(first_vertex, second_vertex)
click to toggle source
# File lib/graphunk/graph.rb, line 67 def edge_exists?(first_vertex, second_vertex) edges.include?(order_vertices(first_vertex, second_vertex)) end
edges()
click to toggle source
# File lib/graphunk/graph.rb, line 12 def edges [].tap do |edge_constructor| vertices.each do |vertex| @representation[vertex].each do |neighbor| edge_constructor << [vertex, neighbor] end end end end
edges_on_vertex(name)
click to toggle source
# File lib/graphunk/graph.rb, line 59 def edges_on_vertex(name) if vertex_exists?(name) edges.select { |edge| edge.include?(name) } else raise ArgumentError, "That vertex does not exist in the graph" end end
neighbors_of_vertex(name)
click to toggle source
# File lib/graphunk/graph.rb, line 49 def neighbors_of_vertex(name) if vertex_exists?(name) edges.select { |edge| edge.include? name }.map do |edge| edge.first == name ? edge.last : edge.first end else raise ArgumentError, "That vertex does not exist in the graph" end end
remove_vertex(name)
click to toggle source
# File lib/graphunk/graph.rb, line 38 def remove_vertex(name) if vertex_exists?(name) edges.each do |edge| remove_edge(edge.first, edge.last) if edge.include?(name) end @representation.delete(name) else raise ArgumentError, "That vertex does not exist in the graph" end end
vertex_exists?(name)
click to toggle source
# File lib/graphunk/graph.rb, line 71 def vertex_exists?(name) vertices.include?(name) end
vertices()
click to toggle source
# File lib/graphunk/graph.rb, line 8 def vertices @representation.keys end
Private Instance Methods
order_vertices(v, u)
click to toggle source
# File lib/graphunk/graph.rb, line 77 def order_vertices(v, u) [v, u].sort end