note 102761 deleted from function.shuffle by danbrown
| From: | danbrown@php.net | Date: | Fri, 04 Mar 2011 14:53:28 +0000 |
| Subject: | note 102761 deleted from function.shuffle by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-177563@lists.php.net to get a copy of this message | ||
Note Submitter: oleh dot naumko at yaN05PAMhoo dot co dot uk
----
The function array_2D_permute published earlier is useful but buggy: when called more than once
within the same script, it keeps all previous values in static $permuted_array, thus creating
duplicates. The corrected version of the function makes use of the additional flag to differentiate
between 1st(external) call of array_2D_permute and all subsequent(recursive, internal) calls.
<?php
# originally published http://uk.php.net/manual/en/function.shuffle.php#62840
# Takes a non-associative 1D (vector) array of items
# and returns an array of arrays with each possible permutation
function array_2D_permute($items, $perms = array(), $isCalledRecursively = false) {
static $permuted_array;
if(!$isCalledRecursively) $permuted_array = array();
if (empty($items)) {
$permuted_array[]=$perms;
} else {
for ($i = count($items) - 1; $i >= 0; --$i) {
$newitems = $items;
$newperms = $perms;
list($foo) = array_splice($newitems, $i, 1);
array_unshift($newperms, $foo);
array_2D_permute($newitems, $newperms, true);
}
return $permuted_array;
}
}
// NB now that this bug has been corrected, both produced results will be identical
$arr=array("Architecture","Mexico");
$result1=array_2D_permute($arr);
print_r($result1);
$result2=array_2D_permute($arr);
print_r($result2);
?>