Skip to content

Instantly share code, notes, and snippets.

@mh-github
Created February 21, 2015 19:34
Show Gist options
  • Select an option

  • Save mh-github/981dbc17ffa7e363f1dc to your computer and use it in GitHub Desktop.

Select an option

Save mh-github/981dbc17ffa7e363f1dc to your computer and use it in GitHub Desktop.
Ruby version of Dendrogram drawing (Python recipe) from http://code.activestate.com/recipes/139422-dendrogram-drawing/
def printDendrogram(t, sep=3)
isPair = lambda do |t|
return t.class == Array && t.length == 2
end
maxHeight = lambda do |t|
if isPair.call(t)
h = [maxHeight.call(t[0]), maxHeight.call(t[1])].max
else
h = t.to_s.length
end
return h + sep
end
activeLevels = {}
traverse = lambda do |t, h, isFirst|
if isPair.call(t)
traverse.call(t[0], h-sep, 1)
s = [" "]*(h-sep)
s << "|"
else
s = t.chars
s << (" ")
end
while s.length < h
s << ("-")
end
if (isFirst >= 0)
s << ("+")
if isFirst > 0
activeLevels[h] = 1
else
activeLevels.delete(h)
end
end
a = activeLevels.keys
a.sort!
a.each do |l|
if s.length < l
while s.length < l
s << (" ")
end
s << ("|")
end
end
puts s.join("")
if isPair.call(t)
traverse.call(t[1], h-sep, 0)
end
end
traverse.call(t, maxHeight.call(t), -1)
end
printDendrogram [ [ ['a' , 'b'] , 'c' ], [ [ 'd' , 'e' ], [ 'f', 'g' ] ] ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment