jueves, 3 de febrero de 2011

List to Tree (using whitespaces to indent) with Groovy

Supose you have a structure like this:













idnamefather
1N1null
11N111
12N121
121N12112
122N12212
13N131
131N13113
1311N1311131
13111N131111311
14N141
2N2null


public class Node {
def id
def name
def father
}

public class NodePrinter {
private void printLeftPad(def source,int pad)
{
for(int i=0;i<pad;i++) print " ";
println source;
}

public int indent(List items,int index,int pad)
{
printLeftPad("${items.get(index).name}",pad);

def current= items.get(index);
int i=index+1;
for(;i<items.size();i++)
{
if( items.get(i).father==current.id )
{
printLeftPad("{",pad);
i=indent(items,i,pad+4);
printLeftPad("}",pad);
}
else
{
if( current.father==items.get(i).father )
{
printLeftPad("${items.get(i).name}",pad);
current=items.get(i);
}
else
{
return i-1;
}
}
}

return i;
}

}

def nodes=[ new Node(id:1,name:'N1',father:null),
new Node(id:11,name:'N11',father:1),
new Node(id:12,name:'N12',father:1),
new Node(id:121,name:'N121',father:12),
new Node(id:122,name:'N122',father:12),
new Node(id:13,name:'N13',father:1),
new Node(id:131,name:'N131',father:13),
new Node(id:1311,name:'N1311',father:131),
new Node(id:13111,name:'N13111',father:1311),
new Node(id:14,name:'N14',father:1),
new Node(id:2,name:'N2',father:null)
];

def printer=new NodePrinter();
printer.indent(nodes,0,4);


This will give us the following result:

N1
{
N11
N12
{
N121
N122
}
N13
{
N131
{
N1311
{
N13111
}
}
}
N14
}
N2


Enjoy it!

No hay comentarios.: