note 17273 deleted from function.array-chunk by jimw
| From: | jimw@php.net | Date: | Tue, 18 Dec 2001 21:05:26 +0000 |
| Subject: | note 17273 deleted from function.array-chunk by jimw | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-23242@lists.php.net to get a copy of this message | ||
I created a counterpoint to the array_chunk function. Let's say you want to distribute an array
of X values among Y buckets. The following function array_distribute(...) will do a roughly balanced
job of this, using the magic of prime numbers.
function is_relatively_prime($a, $b) {
if ($a <= 1 || $b <= 1) {
return false;
}
$divisor = 2;
while ($a > 1 && $b > 1) {
if ($a % $divisor == 0 && $b % $divisor == 0) {
return false;
}
while ($a % $divisor == 0) {
$a = $a / $divisor;
}
while ($b % $divisor == 0) {
$b = $b / $divisor;
}
$divisor++;
}
return true;
}
// split $array into $num_chunks chunks and return chunks in a
// double dim array
function array_distribute($array, $num_chunks) {
$num_chunks = min($num_chunks, count($array));
$return_value = array();
// first, pick $increment, which will be first integer relatively prime to $num_chunks
for ($increment=2; !is_relatively_prime($increment, $num_chunks); $increment++);
$distribution = array();
// next two loops determine size of each chunk
for ($i=0; $i<$num_chunks; $i++) {
$distribution[$i] = 0;
}
for ($i=0; $i<count($array); $i++) {
$chunk = ($i * $increment) % $num_chunks;
$distribution[$chunk]++;
}
// finally, create the chunks
for ($i=0; $i<$num_chunks; $i++) {
$return_value[$i] = array();
for ($j=0; $j<$distribution[$i]; $j++) {
$return_value[$i][$j] = array_shift($array);
}
}
return $return_value;
}
// Calling it like this:
var_dump(array_distribute(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18), 5));
// Will give the following output
array(5) {
[0]=>
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
[1]=>
array(3) {
[0]=>
int(5)
[1]=>
int(6)
[2]=>
int(7)
}
[2]=>
array(4) {
[0]=>
int(8)
[1]=>
int(9)
[2]=>
int(10)
[3]=>
int(11)
}
[3]=>
array(3) {
[0]=>
int(12)
[1]=>
int(13)
[2]=>
int(14)
}
[4]=>
array(4) {
[0]=>
int(15)
[1]=>
int(16)
[2]=>
int(17)
[3]=>
int(18)
}
}