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
Release: 2024-12-01 04:30:13
Original
430 people have browsed it

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.
Copy after login

Example Usage:

Executing the code snippet:

#php a.php
Copy after login

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

hey
hye
ehy
eyh
yeh
yhe
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template