1

I have the following code, which prints all combinations of the given numbers. It returns a fatal error when $numbers contains two equal numbers.

I get the following error:

Fatal error: Maximum execution time of 30 seconds exceeded in
C:/Apache24/htdocs/index.php on line 18

My Code:

<?php
$numbers = array("2","1","4");
$numberofelements = count($numbers);
$factorial = 1;
for ($i=1; $i<=$numberofelements; $i++)
{
         $factorial *= $i;
}
$quantitycombinations = $factorial;
$numbersdrawn = array();
while(true)
{
    $exists = false;
    $numberdrawn1 = "";
    shuffle($numbers);
    $numberdrawn1 = implode("", $numbers);
    strval($numberdrawn1);
    foreach ($numbersdrawn as $value) {
            if(strval($value)==$numberdrawn1)
            {
                $exists = true;
            }
        }
    if(!$exists){
        array_push($numbersdrawn, $numberdrawn1);
        if(count($numbersdrawn)==$quantitycombinations)
        {
            foreach($numbersdrawn as $item)
            {
                echo $item."<br>";          
            }
            break;
        }
    }
}
?>
GrumpyCrouton
  • 8,486
  • 7
  • 32
  • 71
  • Your basic algorithm for this is: generate a random attempt until you find a new one, then once you've created all of them, show them in a list. The problem is that with any repeating digits, you're never going to hit the number of combinations, because they aren't unique. This isn't a problem you can solve with brute force, unless you're smarter about calculating the number of total combinations. – iainn Dec 27 '17 at 22:01
  • See [this question](https://stackoverflow.com/questions/2617055/how-to-generate-all-permutations-of-a-string-in-php) for some alternative approaches. – iainn Dec 27 '17 at 22:02

1 Answers1

0

The while loop doesn't stop until the number of combinations in $numbersdrawn is equal to $factorial. But when there are duplicates, there aren't that many different combinations, because some of the combinations are identical to each other.

E.g. if the numbers are 1, 2, 3, the combinations are 123, 132, 213, 231, 312, 321.

But if the numbers are 1, 2, 2, the combinations are only 122, 212, 221.

You need to divide $factorial by the number of repeated elements to get $quantitycombinations.

Barmar
  • 741,623
  • 53
  • 500
  • 612