我在groovy中有名称或节点的映射,其中key os parent和value依赖于父子。
'A' -> 'B', 'C'
'B' -> 'C'
'C' -> 'D'
'D'
没有叶子的节点未在地图中指定为键。
我需要根据节点的级别为每个节点指定排名。这意味着我想创建新的地图或更改现有的地方,它将包含从没有叶子的节点开始的排名。
'D' -> 100
'C' -> 101
'B' -> 102
'A' -> 103
在groovy中做到这一点的最佳方法是什么?
谢谢。
答案 0 :(得分: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