PHP采取所有组合

标签 php algorithm combinations combinatorics discrete-mathematics

我看到了这个algorithm that will take numbers or words and find all possible 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"; 
    }
?>

它返回:

cat dog
dog cat
cat fish
fish cat
dog fish
fish dog

但这些并不都是真正的组合,所有真正的组合也包括这些:

cat cat
dog dog
fish fish

这就是我需要的,获得所有真实组合的方法:

cat dog
dog cat
cat fish
fish cat
dog fish
fish dog
cat cat
dog dog
fish fish

最佳答案

好的,这是您的代码(顺便说一句,感谢您发布如此有趣且具有挑战性的问题 - 至少对我而言......:-)) - 对所有可能的排列使用递归(由 N ) 给定一个元素数组)

代码:

<?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);

?>

输出:

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
)

提示:通过permutations($words,2),您将能够得到您想要的...

关于PHP采取所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9787051/

相关文章:

php - 在 include 中设置 Twig 变量并在之后使用它

java - 将一个组组合成多个组而不重复

php - 尝试使用复选框创建 sql 查询

javascript - 使用ajax从数据库加载数据时将复选框添加到数据表

algorithm - 检测网络流周期性的有效方法

algorithm - 最短路径 : Picking up cards without duplicates

string - 二元序列相加组合

javascript - 了解 "global"正则表达式

php - LAST_INSERT_ID 在 UPDATE 上不起作用

c++ - 如何在此添加此条件并使其达到最佳状态?