Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

algorithm - PHP take all combinations

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), "
"; 
    }
?>

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :

<?php

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;
}

// Your array
$words = array('cat','dog','fish');

// Get permutation by groups of 3 elements
$pe = permutations($words,3);

// Print it out
print_r($pe);

?>

Output :

Array
(
    [0] => cat cat cat
    [1] => cat cat dog
    [2] => cat cat fish
    [3] => cat dog cat
    [4] => cat dog dog
    [5] => cat dog fish
    [6] => cat fish cat
    [7] => cat fish dog
    [8] => cat fish fish
    [9] => dog cat cat
    [10] => dog cat dog
    [11] => dog cat fish
    [12] => dog dog cat
    [13] => dog dog dog
    [14] => dog dog fish
    [15] => dog fish cat
    [16] => dog fish dog
    [17] => dog fish fish
    [18] => fish cat cat
    [19] => fish cat dog
    [20] => fish cat fish
    [21] => fish dog cat
    [22] => fish dog dog
    [23] => fish dog fish
    [24] => fish fish cat
    [25] => fish fish dog
    [26] => fish fish fish
)

HINT : By permutations($words,2), you'll be able to get exactly what you wanted...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...