0

I found this here PHP take all combinations

I modified it further to include n number of sets to the given array. However i am not able to figure out how to not get any duplicate numbers in a set. for example

If the output is

1 , 1, 3, 4

then it should remove the extra '1' and give it as

1,3,4

similarly if there are 2 outputs.

1,3,4,5 and 4,5,3,1

then it should remove one of the duplicate set as well.

I tried using array_unique and thought it could solve half of the issue however it gave a memory allocation error.

<?php

function permutations($arr,$n)
{
 $res = array();

 foreach ($arr as $w)
 {
       if ($n==1) $res[] = $w;
       else
       {
             $perms = permutations($arr,$n-1);

             foreach ($perms as $p)
             {
                  $res[] = $w." ".$p;
             } 
       }
 }

 return $res;
}

// Your array
$numbers = array(1,2,3,4,5,6,7);

// Get permutation by groups of n elements
for($i=1; $i<8; $i++)
$pe = permutations($numbers,$i);
$pe = array_unique($pe);
// Print it out
print_r($pe);

?>
Community
  • 1
  • 1

0 Answers0