April 27, 2012

php available options

Question by lexvdpoel

Possible Duplicate:
How to generate all permutations of a string in PHP?

I want to make a script in php that will take this input:

12a

And output a result like so:

1, 2, a, 12, 1a, 21, 2a, a1, a2, 12a, 1a2, 21a, 2a1.

I did some research but I cannot find any script that will do this.

Answer by Starx

Here is a modified function from this answer

function permute($str,$i,$n) {
   if ($i == $n)
       print "$strn";
   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 = "12a";
$len = strlen($str);
for($i =0; $i <= $len; $i++) {
   permute($str,0,$i + 1); // call the function.
}
...

Please fill the form - I will response as fast as I can!