2013-08-26 48 views
0

我有groovy中的名称或节点的映射,其中父主键和值取决于父子节点。在Groovy中循环遍历节点集合

'A' -> 'B', 'C' 
'B' -> 'C' 
'C' -> 'D' 
'D' 

没有叶子的节点未在地图中指定为键。

我需要根据它们的级别为每个节点指定排名。这意味着我想创建新的地图或改变现有的地方,它将包含从100开始的排名,没有叶子的节点。

'D' -> 100 
'C' -> 101 
'B' -> 102 
'A' -> 103 

在groovy中做什么最好的方法是什么?

谢谢。

回答

0

你可以尝试这样的事情(运行在GroovyConsole

//the list of nodes 
def nodes = ['A','B','C','D'] 
//the map of children for each node(children are in lists) 
def children = [A:['B', 'C'],B:['C'],C:['D']] 
//the map for the rankings 
def ranking = [:] 

//define closure first so it can be called recursively 
def calculate 
calculate = { 
    if(children.containsKey(it)){ 
     //if key is in children map it has children -> at least rank 1 
     int rank = 1 
     //get children ranks and put it con collection 
     def childrenRanks = children[(it)].collect{calculate(it)} 
     //add max children rank to parent rank and return 
     return rank + childrenRanks.max() 
    }else{ 
     //if key is not on children map is leaf so rank 0 
     return 0 
    } 
} 

nodes.each{ 
    ranking[it] = 100 //fixed value 
    ranking[it] += calculate(it) 
} 

println ranking 
+0

Alfergon,谢谢。什么是孩子:孩子?我如何阅读它? – yart

+1

@yart它是一个地图构造函数。 Groovy默认提供这些。这意味着:“用'children'变量中的值启动'children'字段 – Will

+0

@WillP说的是:D这个例子足够吗?它能解决你的问题吗? – Alfergon