Hayleys code is more compact than mine but here goes.
I find all the possible perms by shuffling the characters around using the shuffle function. all it does is step all the characters one to the left and the first becomes the last. i.e.
1234 becomes 2341.
<?
function shuffle_up($strin)
{
unset($arrayin);
unset($strout);
// cut the incoming string into an array.
for ( $loop=0; $loop<strlen($strin); $loop++ )
{
$arrayin[]=substr($strin, $loop, 1);
}
// store the first character of the array.
$stor=$arrayin[0];
//shuffle all the characters to the left.
for ( $loop=1; $loop<count($arrayin); $loop++ )
{
$arrayin[$loop-1]=$arrayin[$loop];
$strout.=$arrayin[$loop-1];
}
//add the first character back on the end.
$arrayin[count($arrayin)-1]=$stor;
$strout.=$stor;
//return the shuffled string.
return($strout);
}
function makeperms($strin)
{
unset($arrayin);
unset($perms);
// convert the incoming string into an array.
// it seemed logical at the time.!
for ( $loop=0; $loop<strlen($strin); $loop++ )
{
$arrayin[]=substr($strin, $loop, 1);
}
/* create and initialise a few variables.
$permout[0]=$strin; // the return array.
$perm=$strin; // the string to hack up.
$off=0; // any offset for switching.
$switch=2; // distance of chars to switch.
// main loop
for ( $loop2=0; $loop2<(count($arrayin)*count($arrayin)); $loop2++ )
{
// sub loop to process each character in the string. i.e. pass 1234 this will return 2341, 3412, 4124 and 1234
for ( $loop=0; $loop<count($arrayin); $loop++ )
{
$permout[]=$perm;
$perm=shuffle_up($perm);
}
// set up a temp array to store the original permutation in.
// in the first instance it will swap the characters in the first and second positions
// these are then shuffled so 1234 becomes 2134.
// when all the chars have been swapped with their neighbours incease the switch value.
// this then switches the first and third chars. i.e. 1234 becomes 3214 wehich is then shuffled.
unset($tmparr);
for ( $loop=0; $loop<count($arrayin); $loop++ )
{
$tmparr[$loop]=$arrayin[$loop];
}
//switch characters based on what has already been done.
switch($switch)
{
case 2:
$tmparr[1+$off]=$arrayin[0+$off];
$tmparr[0+$off]=$arrayin[1+$off];
$off++;
if ( $off >= (count($arrayin)-1) )
{
$off=0;
$switch=3;
}
break;
case 3:
$tmparr[2+$off]=$arrayin[0+$off];
$tmparr[0+$off]=$arrayin[2+$off];
$off++;
if ( $off >= (count($arrayin)-2) )
{
$off=0;
$switch=4;
}
break;
case 4:
$tmparr[3+$off]=$arrayin[0+$off];
$tmparr[0+$off]=$arrayin[3+$off];
$off++;
if ( $off >= (count($arrayin)-3) )
{
$off=0;
$switch=1;
}
break;
}
// rebuild the string using the temp array
unset($perm);
for ( $loop=0; $loop<count($tmparr); $loop++ )
{
$perm.=$tmparr[$loop];
}
}
// a bit of cleaning up
$tmparr=array_unique($permout);
for ( $loop=0; $loop<count($permout); $loop++ )
{
if ( $tmparr[$loop] != "" && strlen($permout[$loop]) == strlen($strin) )
{
$outarr[]=$permout[$loop];
}
}
//sort the array.
sort($outarr);
// return the array.
return($outarr);
}
?>
hows that?
Mark.