views:

45

answers:

1

If I know I have n records, and I want to do something to a group of r records at a time (basically do stuff to n in batches because n is really large), what is the algorithm for that? Any language is OK (though I'm using PHP).

The algorithm should keep in mind that in the final iteration, there may not be enough records to create a complete group of r.

Recall: to find the total number of r combinations from a set of n records, 
use the combination formula:

C(n,r) = n! / r!(n-r)!

-- Edit -- In case others are interested: I have a CSV (string) with about 10K rows. I was looking for the most efficient way of processing each row of the CSV in chunks of X.

For example, I need to send data from the CSV to a 3rd party via API. The API only allows sending X records at once (which is why I need the chunking).

+2  A: 

use array_chunk().

$chunks = array_chunk($arr, $r);
foreach($chunks as $chunk)
{
   deal_with($chunk);
}
Gabi Purcaru
Exactly what I needed! I didn't realize there was array_chunk().
Joshua McGinnis