Skip to content

Instantly share code, notes, and snippets.

@Maumagnaguagno
Last active November 4, 2018 10:13
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 Maumagnaguagno/24074f8cbc3ab1ce8b402be9dcd6b7dd to your computer and use it in GitHub Desktop.
Save Maumagnaguagno/24074f8cbc3ab1ce8b402be9dcd6b7dd to your computer and use it in GitHub Desktop.
# Based on http://www.graphviz.org/content/generate-directory-tree-dot
def treedot(tree)
nodes = Hash.new {|h,k| h[k] = "node#{h.size}"}
dot = 'digraph tree{
fixedsize=true
splines=ortho
node [style="rounded,filled", fillcolor="#E5E5E5", concentrate=true]'
tree.each {|name,subtree| add(dot, name, subtree, nodes)}
dot << "\n}"
end
def add(dot, name, tree, nodes)
node = nodes[name]
dot << "\n #{node}[label=\"#{name}\" shape=box]"
size = 1
if tree
previous = node
previous_size = 1
tree.each {|name2,subtree|
node2 = nodes[name2]
# Vertical
dot << "\n\n #{previous} -> #{node}_to_#{node2} [arrowhead=none, minlen=#{previous_size}]"
# Horizontal
dot << "\n #{previous = "#{node}_to_#{node2}"} -> #{node2} {rank=same #{previous} [shape=point] #{node2} [label=\"#{name2}\"] }"
size += previous_size = add(dot, name2, subtree, nodes)
}
end
size
end
tree = {
'a1(a)' => {
'b1(a)' => {
'c1(a)' => {
'd1(a)' => nil
},
'c2(a)' => {
'd2(a)' => nil,
'd3(a)' => nil
}
},
'b2(a)' => nil
}
}
#puts treedot({}), '---'
#puts treedot({'a' => nil}), '---'
#puts treedot({'a' => {'b' => nil}}), '---'
puts dot = treedot(tree)
IO.write('treedot.dot', dot)
`graphviz/bin/dot.exe treedot.dot -O -Tpdf`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment