0

我在 groovy 中有名称或节点的映射,其中键 os 父级和值取决于父级子级。

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

没有叶子的节点未指定为映射中的键。

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

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

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

谢谢你。

4

1 回答 1

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
于 2013-08-26T10:54:16.977 回答