If I have this:
def array = [1,2,3,4,5,6]
Is there some built-in which allows me to do this ( or something similar ):
array.split(2)
and get:
[[1,2],[3,4],[5,6]]
?
If I have this:
def array = [1,2,3,4,5,6]
Is there some built-in which allows me to do this ( or something similar ):
array.split(2)
and get:
[[1,2],[3,4],[5,6]]
?
There is nothing builtin to do that but it is not hard to write:
def array = [1,2,3,4,5,6]
int mid = (int) (array.size() / 2)
def left = array[0..mid-1]
def right = array[mid..array.size()-1]
println left
println right
I agree with Chris that there isn't anything built into groovy to handle this (at least for more than 2 partitions), but I interpreted your question to be asking something different than he did. Here's an implementation that does what I think you're asking for:
def partition(array, size) {
def partitions = []
int partitionCount = array.size() / size
partitionCount.times { partitionNumber ->
def start = partitionNumber * size
def end = start + size - 1
partitions << array[start..end]
}
if (array.size() % size) partitions << array[partitionCount * size..-1]
return partitions
}
def origList = [1, 2, 3, 4, 5, 6]
assert [[1], [2], [3], [4], [5], [6]] == partition(origList, 1)
assert [[1, 2], [3, 4], [5, 6]] == partition(origList, 2)
assert [[1, 2, 3], [4, 5, 6]] == partition(origList, 3)
assert [[1, 2, 3, 4], [5, 6]] == partition(origList, 4)
assert [[1, 2, 3, 4, 5], [6]] == partition(origList, 5)
assert [[1, 2, 3, 4, 5, 6]] == partition(origList, 6)
Here's an alternative version, that uses Groovy's dynamic features to add a split method to the List class, that does what you expect:
List.metaClass.split << { size ->
def result = []
def max = delegate.size() - 1
def regions = (0..max).step(size)
regions.each { start ->
end = Math.min(start + size - 1, max)
result << delegate[start..end]
}
return result
}
def original = [1, 2, 3, 4, 5, 6]
assert [[1, 2], [3, 4], [5, 6]] == original.split(2)
Another method using inject and metaClasses
List.metaClass.partition = { size ->
def rslt = delegate.inject( [ [] ] ) { ret, elem ->
( ret.last() << elem ).size() >= size ? ret << [] : ret
}
!rslt.last() ? rslt[ 0..-2 ] : rslt
}
def origList = [1, 2, 3, 4, 5, 6]
assert [ [1], [2], [3], [4], [5], [6] ] == origList.partition(1)
assert [ [1, 2], [3, 4], [5, 6] ] == origList.partition(2)
assert [ [1, 2, 3], [4, 5, 6] ] == origList.partition(3)
assert [ [1, 2, 3, 4], [5, 6] ] == origList.partition(4)
assert [ [1, 2, 3, 4, 5], [6] ] == origList.partition(5)
assert [ [1, 2, 3, 4, 5, 6] ] == origList.partition(6)