Combinations, Dispositions and Permutations in PHP
Solution 1:
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.
Solution 2:
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>';
}
}
Solution 3:
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.