Skip to content

Instantly share code, notes, and snippets.

@GirlBossRush
Created November 2, 2011 23:27
Show Gist options
  • Save GirlBossRush/1335284 to your computer and use it in GitHub Desktop.
Save GirlBossRush/1335284 to your computer and use it in GitHub Desktop.
Graph Implementation (work test 1)
require 'set'
require 'test/unit/assertions'
include Test::Unit::Assertions
class Graph
def initialize
@list = Hash.new
end
attr_accessor :list
def add_direct(node, dep)
@list[node] = dep
#Create dep nodes if nonexistant
dep.each { |n| @list[n] = '' if @list[n].nil? }
end
def dependencies_for(node)
dep_list = Set.new
dep_list += @list[node]
dep_list.each do |x|
dep_list += dependencies_for(x)
end
return dep_list.to_a
end
end
def my_test
puts "Welcome to the test, lets declare some variables."
dep = Graph.new
puts "A: B C"
dep.add_direct('A', %w{ B C } )
puts "B: C E"
dep.add_direct('B', %w{ C E } )
puts "A: B C"
dep.add_direct('A', %w{ B C } )
puts "B: C E"
dep.add_direct('B', %w{ C E } )
puts "C: G"
dep.add_direct('C', %w{ G } )
puts "D: A F"
dep.add_direct('D', %w{ A F } )
puts "E: F"
dep.add_direct('E', %w{ F } )
puts "F: H"
dep.add_direct('F', %w{ H } )
puts "Lets take a look at the graph:\n#{dep.list.inspect}"
puts "Now that's out of the way, lets do some tests"
puts "A: #{dep.dependencies_for('A').inspect}"
puts "B: #{dep.dependencies_for('B').inspect}"
puts "C: #{dep.dependencies_for('C').inspect}"
end
def test_basic
dep = Graph.new
dep.add_direct('A', %w{ B C } )
dep.add_direct('B', %w{ C E } )
dep.add_direct('C', %w{ G } )
dep.add_direct('D', %w{ A F } )
dep.add_direct('E', %w{ F } )
dep.add_direct('F', %w{ H } )
assert_equal( %w{ B C E F G H }, dep.dependencies_for('A'))
assert_equal( %w{ C E F G H }, dep.dependencies_for('B'))
assert_equal( %w{ G }, dep.dependencies_for('C'))
assert_equal( %w{ A B C E F G H }, dep.dependencies_for('D'))
assert_equal( %w{ F H }, dep.dependencies_for('E'))
assert_equal( %w{ H }, dep.dependencies_for('F'))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment