Skip to content

Instantly share code, notes, and snippets.

@vivanov1410
Created May 5, 2013 19:37
Show Gist options
  • Select an option

  • Save vivanov1410/5521924 to your computer and use it in GitHub Desktop.

Select an option

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
<?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