Created
August 17, 2011 20:22
-
-
Save jashmenn/1152505 to your computer and use it in GitHub Desktop.
print a tree in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'spec_helper' | |
describe "GraphExperiments" do | |
JungGraph = Java::EduUciIcsJungGraph | |
before(:each) do | |
n = LazyList[1..Infinity] | |
@tree = JungGraph::DelegateTree.new | |
@tree.setRoot("root") | |
@tree.addChild(n.next, "root", "a") | |
@tree.addChild(n.next, "root", "b") | |
@tree.addChild(n.next, "root", "c") | |
@tree.addChild(n.next, "a", "a1") | |
end | |
it "should have a printer" do | |
tp = TreePrinter.new | |
tp.is_branch = proc{|node| @tree.getChildCount(node) > 0 ? true : false } | |
tp.get_children = proc{|node| @tree.getChildren(node).to_a } | |
puts tp.format(@tree.getRoot) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
root | |
|-- b | |
|-- c | |
`-- a | |
`-- a1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Util | |
class TreePrinter | |
attr_accessor :is_branch | |
attr_accessor :get_children | |
attr_accessor :format_node | |
attr_accessor :skip_root_node | |
def initialize | |
@arms = Hash.new("| ") | |
@arms[""] = "" | |
@arms["`"] = " " | |
@out = "" | |
@is_branch = proc{|node| FileTest.directory?(node) && FileTest.readable?(node) } | |
@get_children = proc{|node| node.children(false).sort} | |
@format_node = proc{|node| node.to_s} | |
@skip_root_node = false | |
end | |
def visit(path, leader, tie, arm, node) | |
if(@root == node) && skip_root_node | |
# skip | |
else | |
node_str = @format_node.call(node) | |
@out << "#{leader}#{arm}#{tie}#{node_str}\n" | |
end | |
visitChildren(node, leader + @arms[arm]) | |
@out | |
end | |
def visitChildren(path, leader) | |
kids = [] | |
if(@root == path) && skip_root_node | |
kids = path | |
else | |
return unless @is_branch.call(path) | |
kids = @get_children.call(path) | |
end | |
return if kids.empty? | |
arms = Array.new(kids.length - 1, "|") << "`" | |
pairs = kids.zip(arms) | |
pairs.each { |e| visit(path, leader, "-- ", e[1], e[0]) } | |
end | |
def format(root) | |
@root = root | |
visit root, "", "", "", root | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment