<?php
// function to generate and print all N! permutations of $str. (N = strlen($str)).
function permute($str,$i,$n,$len)
{
global $ret;
if ($i == $n){
if(in_array(substr($str,0,$len),$ret)==false){$ret[]=substr($str,0,$len);}
}else {
for ($j = $i; $j < $n; $j++) {
swap($str,$i,$j);
permute($str, $i+1, $n, $len);
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;
}
$ret = array();
$str = "123456";
permute($str,0,strlen($str), 3); // call the function.
?>
preferences:
35.16 ms | 402 KiB | 5 Q