I have functions of permutation :
function permutations($letters,$num)
{
$last = str_repeat($letters[0],$num);
$result = array();
while($last != str_repeat($this->lastchar($letters),$num))
{
$result[] = $last;
$last = $this->char_add($letters,$last,$num-1);
}
$result[] = $last;
return $result;
}
function char_add($digits,$string,$char)
{
error_reporting(0);
if($string[$char] < $this->lastchar($digits))
{
$string[$char] = $digits[strpos($digits,$string[$char])+1];
return $string;
}
else
{
$string = $this->changeall($string,$digits[0],$char);
return $this->char_add($digits,$string,$char-1);
}
}
function lastchar($string)
{
return $string[strlen($string)-1];
}
function changeall($string,$char,$start = 0,$end = 0)
{
if($end == 0) $end = strlen($string)-1;
for($i=$start;$i<=$end;$i++){
$string[$i] = $char;
}
return $string;
}
Example to run this :
print_r($this->permutations('1234',2));
And results will be:
Array(
[0] => 11
[1] => 12
[2] => 13
[3] => 14
[4] => 21
[5] => 22
[6] => 23
[7] => 24
[8] => 31
[9] => 32
[10] => 33
[11] => 34
[12] => 41
[13] => 42
[14] => 43
[15] => 44)
It can run well. However, when I run with greater number of permutation like : $this->permutations('1234',5) , the script will cause memory exhaustion.
What can I change to optimize the functions ?
ini_set('memory_limit', '1G');
is a temporary fix. \$\endgroup\$ – 54 69 6D Jul 3 '16 at 21:57