blogscot
blogscot

Reputation: 41

Creating a lists of sums from a list

Is there a groovier way of doing this? That is, create a new list from the sum of groups of 3 numbers from the original list.

    myList = [1,2,3,4,5,6,7,8,9]
    newList = []

    while (myList.size > 0) {
      newList.add(myList.pop() + myList.pop() + myList.pop())
    }

    println newList.reverse()

    [6, 15, 24]

Upvotes: 3

Views: 93

Answers (2)

Nathan Hughes
Nathan Hughes

Reputation: 96394

You can group the list into sublists of 3 elements with collate:

groovy:000> myList = [1,2,3,4,5,6,7,8,9]
===> [1, 2, 3, 4, 5, 6, 7, 8, 9]
groovy:000> myList.collate(3)
===> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Then sum each sublist; the sum can be done with inject:

groovy:000> myList.collate(3)*.inject(0) { sum, i -> sum + i }
===> [6, 15, 24]

or just use this convenience method sum

groovy:000> myList.collate(3)*.sum()
===> [6, 15, 24]

Upvotes: 4

kdabir
kdabir

Reputation: 9868

How about this:

myList.collate(3).collect {it.sum()}

or with just a fine use of spread operator *

myList.collate(3)*.sum()

Upvotes: 5

Related Questions