Skip to content

Instantly share code, notes, and snippets.

@jashmenn
Created August 17, 2011 20:22
Show Gist options
  • Save jashmenn/1152505 to your computer and use it in GitHub Desktop.
Save jashmenn/1152505 to your computer and use it in GitHub Desktop.
print a tree in ruby
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
root
|-- b
|-- c
`-- a
`-- a1
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