tags:

views:

49

answers:

2

I have an array containing an unknown number of items that I would like to split into separate arrays so that each separate array contains no more than 4 items. What is the best way to do this in Groovy? Thanks!

+4  A: 

We had this here: http://stackoverflow.com/questions/2924395/groovy-built-in-to-split-an-array-into-equal-sized-subarrays

I came up with this:

List.metaClass.partition = { size ->
  def rslt = delegate.inject( [ [] ] ) { ret, elem ->
    ( ret.last() << elem ).size() >= size ? ret << [] : ret
  }
  !rslt.last() ? rslt[ 0..-2 ] : rslt
}

def list = [1, 2, 3, 4, 5, 6].partition( 4 )

Which should give you:

[ [ 1, 2, 3, 4 ], [ 5, 6 ] ]
tim_yates
+2  A: 

Answer by tim_yates is cool, but it throws java.lang.ArrayIndexOutOfBoundsException on empty lists (for example: [].partition(4)). This can be fixed in this way:

List.metaClass.partition = {size ->
    if (!delegate)
        return []

    def rslt = delegate.inject([[]]) {ret, elem ->
        (ret.last() << elem).size() >= size ? (ret << []) : ret
    }
    !rslt.last() ? rslt[0..-2] : rslt
}

assert [].partition(4) == []
assert [1, 2, 3, 4, 5, 6].partition(4) == [[1, 2, 3, 4], [5, 6]]
Rorick
good catch! Could also turn last line into `!rslt[ 0 ] ? [] : !rslt.last() ? rslt[ 0..-2 ] : rslt`
tim_yates