Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combinations, Dispositions and Permutations in PHP

What is the most efficient way to generate all the combinations, dispositions and permutations of an array in PHP?

like image 977
Alix Axel Avatar asked Nov 05 '09 10:11

Alix Axel


3 Answers

Here is code to get all permutations:

http://php.net/manual/en/function.shuffle.php#90615

With the code to get the power set, permutations are those of maximal length, the power set should be all combinations. I have no idea what dispositions are, so if you can explain them, that would help.

like image 148
Victor Liu Avatar answered Oct 25 '22 13:10

Victor Liu


You can use this class: http://pear.php.net/package/Math_Combinatorics

and use it like:

$combinatorics = new Math_Combinatorics;

$words_arr = array(
    'one'   => 'a',
    'two'   => 'b',
    'three' => 'c',
    'four'  => 'd',
    );

for ($i=count($words_arr)-1;$i>=1;$i--) {
    echo '<br><br>' . $i . ':<br>';
    $combinations_arr = $combinatorics->combinations($words_arr, $i);
    foreach ($combinations_arr as $combinations_arr_item) {
        echo implode(', ', $combinations_arr_item) . '<br>';
    }
}
like image 33
leticia Avatar answered Oct 25 '22 13:10

leticia


I'd like to suggest my solution of a CombinationsGenerator, which generates combinations of array items.

It's limited to all combinations are of the full length, and not repeats any item. But I believe implementation would not be too hard.

class CombinationsGenerator
{
    public function generate(array $list): \Generator
    {
        if (count($list) > 2) {
            for ($i = 0; $i < count($list); $i++) {
                $listCopy = $list;

                $entry = array_splice($listCopy, $i, 1);
                foreach ($this->generate($listCopy) as $combination) {
                    yield array_merge($entry, $combination);
                }
            }
        } elseif (count($list) > 0) {
            yield $list;

            if (count($list) > 1) {
                yield array_reverse($list);
            }
        }
    }
}

$generator = new \CombinationsGenerator();

foreach ($generator->generate(['A', 'B', 'C', 'D']) as $combination) {
    var_dump($combination);
}

It's in PHP7 style, it uses a \Generator 'cause I believe there are good reasons for doing it.

like image 26
hejdav Avatar answered Oct 25 '22 12:10

hejdav