2

This question has been asked in many forms. I want to take an array in PHP and get all possible combinations / permutations. I want both permutations of the whole set as well as a partial set.

My twist on this question is asking how can I remove sequential duplicates from within the result items. I got close to what I wanted by using " PHP take all combinations " and adding a function:

$words = array('a','b','c');
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;
}

function get_all_permutations($words=array())
{
    $r = array();
    for($i=sizeof($words);$i>0;$i--)
    {
        $r = array_merge(permutations($words,$i),$r);
    }
    return $r;
}

$permutations = get_all_permutations($words);
print_r($permutations);

That will output:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => a a
    [4] => a b
    [5] => a c
    [6] => b a
    [7] => b b
    [8] => b c
    [9] => c a
    [10] => c b
    [11] => c c
    [12] => a a a
    [13] => a a b
    [14] => a a c
    [15] => a b a
    [16] => a b b
    [17] => a b c
    [18] => a c a
    [19] => a c b
    [20] => a c c
    [21] => b a a
    [22] => b a b
    [23] => b a c
    [24] => b b a
    [25] => b b b
    [26] => b b c
    [27] => b c a
    [28] => b c b
    [29] => b c c
    [30] => c a a
    [31] => c a b
    [32] => c a c
    [33] => c b a
    [34] => c b b
    [35] => c b c
    [36] => c c a
    [37] => c c b
    [38] => c c c
)

I know I could look through the output once the set has been generated, but is it possible to remove the sequential duplicates during generation?

Examples which should be transformed / removed:

  • c c c would be the same as c
  • c c b would be the same as c b
  • c c c c c would also be the same as c (if the set was larger)

Notes:

  • I'm not great with recursion but there is probably a fancy way to combine the two functions I have into one.
  • Right now the output sets are strings but I don't mind if they are arrays instead (if that makes things easier)
Community
  • 1
  • 1
cwd
  • 47,510
  • 50
  • 154
  • 194

1 Answers1

0

You could pass the permutations array as a reference (with a proceeding ampersand) in as a third parameter of permutations() and run a in_array() check before adding a value. However this would be far less performant than removing duplicates at the end of get_all_permutation()

thelastshadow
  • 3,020
  • 3
  • 31
  • 33