I saw this algorithm that will take numbers or words and find all possible combinations
And I’m using it, but it does NOT return all “real” combinations.
PHP:
<?php
require_once 'Math/Combinatorics.php';
$words = array('cat', 'dog', 'fish');
$combinatorics = new Math_Combinatorics;
foreach($combinatorics->permutations($words, 2) as $p) {
echo join(' ', $p), "\n";
}
?>
And it returns:
cat dog
dog cat
cat fish
fish cat
dog fish
fish dog
But these are not all real combinations, all real combinations includes these too:
cat cat
dog dog
fish fish
And that is what I need, the method to get all real combinations:
cat dog
dog cat
cat fish
fish cat
dog fish
fish dog
cat cat
dog dog
fish fish
OK, here’s your code (and btw, thanks for posting such an interesting and challenging problem – at least for me… :-)) – using recursion for all possible permutations (by N) given an array of elements)
Code :
Output :
HINT : By
permutations($words,2), you’ll be able to get exactly what you wanted…