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(&$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!