gpt4 book ai didi

algorithm - Groovy 中的简单排名算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:10 25 4
gpt4 key购买 nike

我有一个简短的常规算法,用于根据食物的评分为食物分配排名。这可以在 groovy 控制台中运行。该代码运行完美,但我想知道是否有更多 Groovy 或功能性代码编写方式。如果可能的话,认为摆脱 previousItemrank 局部变量会很好。

def food = [
[name:'Chocolate Brownie',rating:5.5, rank:null],
[name:'Fudge', rating:2.1, rank:null],
[name:'Pizza',rating:3.4, rank:null],
[name:'Icecream', rating:2.1, rank:null],
[name:'Cabbage', rating:1.4, rank:null]]

food.sort { -it.rating }

def previousItem = food[0]
def rank = 1
previousItem.rank = rank
food.each { item ->
if (item.rating == previousItem.rating) {
item.rank = previousItem.rank
} else {
item.rank = rank
}
previousItem = item
rank++
}

assert food[0].rank == 1
assert food[1].rank == 2
assert food[2].rank == 3
assert food[3].rank == 3 // Note same rating = same rank
assert food[4].rank == 5 // Note, 4 skipped as we have two at rank 3

建议?

最佳答案

这是我的解决方案:

def rank = 1
def groupedByRating = food.groupBy { -it.rating }
groupedByRating.sort().each { rating, items ->
items.each { it.rank = rank }
rank += items.size()
}

关于algorithm - Groovy 中的简单排名算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2950799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com