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

How to Generate All Permutations of a String in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-01 04:30:13543browse

How to Generate All Permutations of a String in PHP?

Generating Permutations of a String in PHP

Question:

How can one generate all possible permutations of all characters in a given string using PHP?

Answer:

To generate all permutations of a string, you can utilize a backtracking-based approach that systematically explores all possible combinations.

Implementation:

// function to generate and print all N! permutations of $str. (N = strlen($str)).
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 to swap the char at pos $i and $j of $str.
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.

Example Usage:

Executing the code snippet:

#php a.php

will generate and print all possible permutations of the string "hey":

hey
hye
ehy
eyh
yeh
yhe

The above is the detailed content of How to 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