Home >Backend Development >PHP Tutorial >How Can I Generate All Permutations of a String in PHP?

How Can I Generate All Permutations of a String in PHP?

DDD
DDDOriginal
2024-12-05 09:18:19532browse

How Can I Generate All Permutations of a String in PHP?

Permutations of a String in PHP

In PHP, generating all permutations of characters within a string involves an algorithm that systematically explores all possible combinations.

Backtracking Approach

One effective approach is backtracking. Here's the PHP implementation:

function permute($str,$i,$n) {
   if ($i == $n)
       print "$str\n";
   else {
        for ($j = $i; $j < $n; $j++) {
          swap($str,$i,$j);
          permute($str, $i+1, $n);
          swap($str,$i,$j); // backtrack.
       }
   }
}
function swap(&amp;$str,$i,$j) {
    $temp = $str[$i];
    $str[$i] = $str[$j];
    $str[$j] = $temp;
}   

$str = "hey";
permute($str,0,strlen($str)); // call the function.

Explanation

  • The permute() function systematically explores all possible permutations.
  • It recursively calls itself with increasing values of $i, the index of the character being swapped.
  • The swap() function exchanges the characters at indices $i and $j.
  • The recursion backtracks when the end of the string is reached, printing the resulting permutation.

Output

Executing the code with $str = "hey" produces the expected output:

hey
hye
ehy
eyh
yeh
yhe

The above is the detailed content of How Can I Generate All Permutations of a String in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn