Skip to content

Instantly share code, notes, and snippets.

@jagedn
Last active June 14, 2019 10:06
Show Gist options
  • Save jagedn/1c4ca25986bac8c4c78281a7b92d5be5 to your computer and use it in GitHub Desktop.
Save jagedn/1c4ca25986bac8c4c78281a7b92d5be5 to your computer and use it in GitHub Desktop.
initial=5
depth=15
class Node {
String id
int depth
Boolean isLeft
int value
Node left
Node right
String toString(){
String ret = "$id [label=\"$value ${isLeft?'L':'R'}\"]\n"
if( left && left.value ){
ret += left
ret += "$id -> $left.id\n"
}
if( right && right.value ){
ret += right
ret += "$id -> $right.id\n"
}
ret
}
int incLeft(){
(value-1).intdiv(3)
}
int incRight(){
value*2
}
void incDepth(){
if( (value-1) % 3 == 0)
left = new Node(id:id+'L',depth:depth+1,value:incLeft(),isLeft:true)
right = new Node(id:id+'R',depth:depth+1,value:incRight(),isLeft:false)
}
}
class BinaryTree {
Node root
BinaryTree init(int value) {
root = new Node(id:'O',depth:0,value:value)
this
}
void incDepth(){
incDepth(root)
}
void incDepth(Node cursor){
if( !cursor.left && !cursor.right){
if( !cursor.value )
return
if( !cursor.depth ){
cursor.incDepth()
return
}
if( ((cursor.value & (cursor.value - 1)) == 0)==false ){
cursor.incDepth()
}
return
}
if( cursor.left ){
incDepth(cursor.left)
}
if( cursor.right ){
incDepth(cursor.right)
}
}
String toString(){
String ret = root.toString()
ret
}
}
def tree = new BinaryTree()
tree.init(initial)
(0..depth).each{
tree.incDepth()
}
println "@startdot\n"
println "digraph world {\n"
println tree
println "}\n"
println "@enddot\n"
@jagedn
Copy link
Author

jagedn commented Jun 13, 2019

Copiar el código y pegar en http://groovyconsole.appspot.com/
Ajustar la semilla y profundidad (si supera una profundidad de 18 aprox tendrás problemas para generar el gráfico por la cantidad de nodos)

Ejecutar y copiar el Output en https://planttext.com/
pulsar Refresh

@jagedn
Copy link
Author

jagedn commented Jun 14, 2019

Por ejemplo con semilla 5 y profundidad 15 obtenemos este diagrama

image

@jagedn
Copy link
Author

jagedn commented Jun 14, 2019

con semilla 222 obtenemos
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment