Skip to content

Instantly share code, notes, and snippets.

@thutch
Last active January 1, 2016 03:19
Show Gist options
  • Save thutch/8084791 to your computer and use it in GitHub Desktop.
Save thutch/8084791 to your computer and use it in GitHub Desktop.
OO Recursive Search
class LeafNode
attr_accessor :name
def initialize(name)
@id = name
end
def find_node_named(name)
if @id == name
return self
else
nil
end
end
end
require './node'
require './leafNode'
require 'test/unit'
class LeafNodeTest < Test::Unit::TestCase
def setup
@rootNode = Node.new("root")
@child1 = Node.new("1")
@child2 = Node.new("2")
@child3 = Node.new("3")
@child4 = Node.new("4")
@child5 = Node.new("5")
@leafNodeA = LeafNode.new("A")
@leafNodeB = LeafNode.new("B")
@rootNode.add_child(@child1)
@rootNode.add_child(@child2)
@child1.add_child(@child3)
@child3.add_child(@child4)
@child2.add_child(@child5)
@child4.add_child(@leafNodeA)
@child5.add_child(@leafNodeB)
end
def test_find_node
assert_same(@rootNode, @rootNode.find_node_named("root"))
assert_same(@child1, @rootNode.find_node_named("1"))
assert_same(@child4, @rootNode.find_node_named("4"))
assert_same(nil, @rootNode.find_node_named("9"))
assert_same(@leafNodeA, @rootNode.find_node_named("A"))
assert_same(@leafNodeB, @rootNode.find_node_named("B"))
end
end
class Node
attr_accessor :name
def initialize(name)
@name = name
@children = Array.new
end
def add_child(child)
@children << child
end
def find_node_named(name)
if @name == name
return self
end
@children.each do |child|
found = child.find_node_named(name)
if(found != nil)
return found
end
end
nil
end
end
require './node'
require 'test/unit'
class NodeTest < Test::Unit::TestCase
def setup
@rootNode = Node.new("root")
@child1 = Node.new("1")
@child2 = Node.new("2")
@child3 = Node.new("3")
@child4 = Node.new("4")
@child5 = Node.new("5")
@child6 = Node.new("6")
@rootNode.add_child(@child1)
@rootNode.add_child(@child2)
@child1.add_child(@child3)
@child3.add_child(@child4)
@child3.add_child(@child5)
@child2.add_child(@child6)
end
def test_find_node
assert_same(@rootNode, @rootNode.find_node_named("root"))
assert_same(@child1, @rootNode.find_node_named("1"))
assert_same(@child4, @rootNode.find_node_named("4"))
assert_same(@child6, @rootNode.find_node_named("6"))
assert_same(nil, @rootNode.find_node_named("9"))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment