Drop top N items

1 view
Skip to first unread message

DanMonroe

unread,
Apr 21, 2009, 6:00:28 PM4/21/09
to Groovy Sydney
HI All,

Hopefully this is an easy question.

Given an unsorted list of numbers, I need to "drop" or disregard N
number of the highest numbers. Then I need to print the list in
original order and show which numbers were dropped.

for example, given:

def myList = [ 5, 2, 7, 9, 7, 3, 1 ]
def highNumbersToDrop = 2

// I need to...

myList.each() { thisItem ->

println thisItem

}

// having a result of something like:

5
2
7 - dropped
9 - dropped
7
3
1

My question is how to keep track of which numbers were "dropped" so
that when I display the list, I can add the " - dropped" text.

Thanks in advance,
Dan

Paul King

unread,
Apr 28, 2009, 8:11:20 AM4/28/09
to groovy...@googlegroups.com

Never saw a reply. I guess there will be several ways, here's one:

def myList = [ 5, 2, 7, 9, 7, 3, 1 ]
def highNumbersToDrop = 2
def positionedList = [:]
def sortedList = [:]
myList.eachWithIndex{ item, index -> positionedList[index] = item }
positionedList.sort{ -it.value }.eachWithIndex{ e, index -> if (index >= highNumbersToDrop) sortedList << e }
myList.eachWithIndex{ item, index -> print item; if (!(index in sortedList.keySet())) print ' - dropped'; println() }


Paul.
Reply all
Reply to author
Forward
0 new messages