Created
May 5, 2013 19:37
-
-
Save vivanov1410/5521924 to your computer and use it in GitHub Desktop.
Tasuku 2. Create a method that display all possible permutations in a string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| # basic operation counter | |
| $count = 0; | |
| # prints all n! permutations of $str, $start - start index, $len - string length | |
| function permute($str, $start, $len) { | |
| if($start == $len) { | |
| print "$str\n" . "<br/>"; | |
| return; | |
| } | |
| for($i = $start; $i < $len; $i++) { | |
| if($start != $i) | |
| swap($str, $start, $i); | |
| permute($str, $start+1, $len); | |
| } | |
| } | |
| # swaps characters with index $i and $j in $str | |
| function swap(&$str, $i, $j) { | |
| # basic operation here is comparison | |
| global $count; | |
| $count++; | |
| $temp = $str[$i]; | |
| $str[$i] = $str[$j]; | |
| $str[$j] = $temp; | |
| } | |
| $str = "abcde"; | |
| print permute($str, 0, strlen($str)); | |
| print $count; | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment