Forum Moderators: coopster

Message Too Old, No Replies

php permutations

         

k8tie

12:35 pm on Feb 17, 2003 (gmt 0)

10+ Year Member



Hi
I am having problems as I would like to take values out of an array
eg $name = array (2,3,4);

and would then like to produce all the permutations of them

eg
2,3,4
3,4,2
4,3,2
2,4,3
3,2,4
4,2,3

Does anyone know how to do this /have the code to do this?

Thanks

crypto

5:16 am on Feb 18, 2003 (gmt 0)

10+ Year Member



Try this out. Will work for any array :)

<?
//Put your array here
$yourArr=array("[val1]","[val2]","[val3]");

$n=count($yourArr);

for ($i=0; $i <= $n; $i++) $pArr[$i]=$i; //The permutation array.

function PrintPerm()
{
global $yourArr,$pArr,$n;

for ($i=1; $i <= $n; $i++) echo $yourArr[$pArr[$i]-1];
echo "<br>";

return;
}

function swapThem($i,$j)
{
global $pArr;

$temp = $pArr[$i];
$pArr[$i] = $pArr[$j];
$pArr[$j] = $temp;
}

function NextPerm()
{
global $pArr,$n;

$k = $n-1;
while ($pArr[$k] > $pArr[$k+1]) $k--;
if ($k == 0) return(0);
else
{
$j = $n;
while ($pArr[$k] > $pArr[$j]) $j--;
swapThem($j,$k);
$r = $n;
$s = $k+1;
while ($r > $s)
{
swapThem($r,$s);
$r--;
$s++;
}
}
PrintPerm();
return(1);
}

//Print the array values
PrintPerm();
while (NextPerm()); //Permute and print
?>

k8tie

7:21 pm on Feb 18, 2003 (gmt 0)

10+ Year Member



Thanks :)

k8tie

8:43 pm on Feb 18, 2003 (gmt 0)

10+ Year Member



I already have an array that has values in it from previous calculation called $name.
However, when I try to change:

$yourArr=array("[val1]","[val2]","[val3]");

$n=count($yourArr);

to:

$yourArr = count($name);

$n=count($yourArr);

there is no print out on the screen. I am sure the values are in $name but this won't pass on. Am I using the wrong syntax?

andreasfriedrich

8:50 pm on Feb 18, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



>>$yourArr = count($name);

>>$n=count($yourArr);

should read

$yourArr = $name;

$n = count($yourArr);

You donīt want the size of the array in both $yourArr and $n!

Andreas