Loop through nodes collection in Groovy -


i have map of names or nodes in groovy key os parent , value dependent on parent childs.

'a' -> 'b', 'c' 'b' -> 'c' 'c' -> 'd' 'd' 

the node doesn't have leafs not specified key in map.

i need specify ranking every of node based on level. means create new map or change existing contain rank starting 100 nodes doesn't have leafs.

'd' -> 100 'c' -> 101 'b' -> 102 'a' -> 103 

what best way in groovy?

thank you.

you try (runs on groovyconsole)

//the list of nodes def nodes = ['a','b','c','d'] //the map of children each node(children in lists) def children = [a:['b', 'c'],b:['c'],c:['d']] //the map rankings def ranking = [:]   //define closure first can called recursively def calculate calculate = {     if(children.containskey(it)){         //if key in children map has children -> @ least rank 1         int rank = 1         //get children ranks , put con collection         def childrenranks = children[(it)].collect{calculate(it)}         //add max children rank parent rank , return         return rank + childrenranks.max()     }else{         //if key not on children map leaf rank 0         return 0     } }  nodes.each{     ranking[it] = 100 //fixed value     ranking[it] += calculate(it) }  println ranking 

Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -