Alex Rivera | Logout

PHP take all combinations

Asked 2012-03-20T12:48:13.510
8

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
Edit
Report

1 Answer

0

Your current code gives you permutations, simply add duplicates:

foreach($words as $w) {
    echo "$w $w\n";    
}

What's the problem?

answered 2012-03-20T13:00:03.060

Your Answer