# Month: August 2009

## Weird Snippet to Divide an Array [ruby]

Dividing an array of *n* elements into *pieces *subarrays is a little bit trickier than it seems. Each subarray will contain *chunk_size = n / pieces* elements and *n % pieces* will remain unassigned, and need to be distributed to the subarrays. You can do this in many ways, but in this case we will assign the first remaining element to the first subarray, and so on. So the first *n%pieces* subarrays will contain *n/pieces+1* elements.

def chunk_array(a,pieces)

cs = a.length / pieces #chunk size

r = -1*(a.length%pieces) #remaining elements to be asigned to a chunk

(0..pieces-1).map{|i| r+=1; a[i*cs..(i+1)*cs-1] + (r<1 ? a[r-1..r-1] : [])}

end