note 102761 deleted from function.shuffle by danbrown

[email protected]
Newsgroups php.notes
Message-ID <[email protected]>
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);
?>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.