I need a function that will return all possible unique variations of an input array, but not repeat the array elements so [a,b,c] and [b,c,a] are the same.
I have a working function that outputs the desired result using a binary count. So for an input array of array("a", "b", "c")
it will output:
Array
(
[0] => Array
(
[0] => c
)
[1] => Array
(
[0] => b
)
[2] => Array
(
[0] => b
[1] => c
)
[3] => Array
(
[0] => a
)
[4] => Array
(
[0] => a
[1] => c
)
[5] => Array
(
[0] => a
[1] => b
)
[6] => Array
(
[0] => a
[1] => b
[2] => c
)
)
However I'm finding that for arrays with 20 or more elements the code runs out of memory. I suspect because of the $binary
variable
The code I'm using is:
function find_unique_combinations($arr){
$bits = count($arr);
$dec = 1;
while($dec < pow(2, $bits)) {
$binary = str_split(str_pad(decbin($dec), $bits, '0', STR_PAD_LEFT));
$curterm = array();
$i = 0;
while($i < ($bits)){
if($binary[$i] == 1) {
$curterm[] = $arr[$i];
}
$i++;
}
$terms[] = $curterm;
$dec++;
}
return $terms;
}
The error message im getting is
Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 36 bytes)
php.ini is currently set to 512MB, I'd rather fix the code than allocate more memory if possible.