Skip to content

Instantly share code, notes, and snippets.

@brianstorti
Created April 6, 2013 00:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianstorti/5323724 to your computer and use it in GitHub Desktop.
Save brianstorti/5323724 to your computer and use it in GitHub Desktop.
class Node
attr_reader :name
def initialize(name)
@name = name
@descendants = []
end
def add_edge(descendant, weight)
@descendants << {:node => descendant, :weight => weight}
end
def to_s
"#{@name} -> [#{formatted_descendants.join(' ')}]"
end
private
def formatted_descendants
descendants = []
@descendants.each do |descendant|
descendants << "#{descendant[:node].name}-#{descendant[:weight]}"
end
descendants
end
end
require_relative "node"
require_relative "weighted_directed_graph"
graph = WeightedDirectedGraph.new
graph.add_node(Node.new(:a))
graph.add_node(Node.new(:b))
graph.add_node(Node.new(:c))
graph.add_node(Node.new(:d))
graph.add_node(Node.new(:e))
graph.add_edge(:a, :b, 5)
graph.add_edge(:b, :c, 4)
graph.add_edge(:c, :d, 8)
graph.add_edge(:d, :c, 8)
graph.add_edge(:d, :e, 6)
graph.add_edge(:a, :d, 5)
graph.add_edge(:c, :e, 2)
graph.add_edge(:e, :b, 3)
graph.add_edge(:a, :e, 7)
puts graph[:a] # => a -> [b-5 d-5 e-7]
puts graph[:b] # => b -> [c-4]
puts graph[:c] # => c -> [d-8 e-2]
puts graph[:d] # => d -> [c-8 e-6]
puts graph[:e] # => e -> [b-3]
class WeightedDirectedGraph
def initialize
@nodes = {}
end
def add_node(node)
@nodes[node.name] = node
end
def add_edge(from, to, weight)
raise ArgumentError, "Both nodes need to exist" unless @nodes[from] && @nodes[to]
@nodes[from].add_edge(@nodes[to], weight)
end
def [](name)
@nodes[name]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment