Simple ranking algorithm in Groovy

Posted by Richard Paul on Stack Overflow See other posts from Stack Overflow or by Richard Paul
Published on 2010-06-01T14:52:45Z Indexed on 2010/06/01 15:33 UTC
Read the original article Hit count: 388

Filed under:
|
|

I have a short groovy algorithm for assigning rankings to food based on their rating. This can be run in the groovy console. The code works perfectly, but I'm wondering if there is a more Groovy or functional way of writing the code. Thinking it would be nice to get rid of the previousItem and rank local variables if possible.

def food = [
  [name:'Chocolate Brownie',rating:5.5, rank:null],
  [name:'Pizza',rating:3.4, rank:null],
  [name:'Icecream', rating:2.1, rank:null],
  [name:'Fudge', 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

Suggestions?

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about groovy