Skip to content

Instantly share code, notes, and snippets.

@ayuusweetfish
Created January 16, 2019 10:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayuusweetfish/bce25cd3010ee9fba359fc919e82a380 to your computer and use it in GitHub Desktop.
Save ayuusweetfish/bce25cd3010ee9fba359fc919e82a380 to your computer and use it in GitHub Desktop.
Generate binary tree images with Graphviz and ImageMagick
if #arg < 3 then
print('Usage: ' .. arg[0] .. ' <hor-skip> <ver-skip> <node> [<node> ...]')
return
end
local horskip = tonumber(arg[1])
local verskip = tonumber(arg[2])
local nodes = {}
for i = 3, #arg do
nodes[i - 2] = tonumber(arg[i])
end
table.sort(nodes)
print('graph G {')
print(' node [shape=circle,fontname="Helvetica",fontsize=18,width=.5,height=.5,fixedsize=true];')
local level, level_max = 0, 0
while (1 << level_max) <= nodes[#nodes] do
level_max = level_max + 1
end
for idx, u in ipairs(nodes) do
if u > 1 then
print(string.format(' %d -- %d', u // 2, u))
end
while (1 << level) <= u do level = level + 1 end
local offsetx = horskip * ((1 << (level_max - level)) - 1) / 2
local x = offsetx + horskip * (1 << (level_max - level)) * (u - (1 << (level - 1)))
local y = verskip * (level_max - level)
print(string.format(' %d [pos="%d,%d",label=%d]', u, x, y, idx))
end
print('}')
#!/bin/sh
lua bintree.lua 50 60 1 2 3 4 5 6 7 10 11 14 15 | neato -n -Tpng | montage -label Proper - -pointsize 24 -geometry +0+0 proper.png
lua bintree.lua 50 60 1 2 3 4 5 6 7 8 9 10 | neato -n -Tpng | montage -label Complete - -pointsize 24 -geometry +0+0 complete.png
lua bintree.lua 50 60 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | neato -n -Tpng | montage -label Perfect - -pointsize 24 -geometry +0+0 perfect.png
montage proper.png complete.png perfect.png -geometry +36+6 - | convert - -scale 50% all.png
rm proper.png complete.png perfect.png
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment