7

我看到这个algorithm that will take numbers or words and find all possible combinationsPHP采取一切组合

而且我使用它,但它不会返回所有的“真实”的组合。

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 
+0

你为什么不自己添加这些组合?看起来很简单,可以循环浏览数据并手动添加对。 – 2012-03-20 12:49:51

+0

这与以前的问题不一样吗?你似乎对答案有所怀疑。为什么不在那里继续? – Nanne 2012-03-20 12:52:16

+3

Math_Combinatorics - “返回给定集合和子集大小的所有组合和排列的包,保留关联数组。”这里的关键是“不重复”。 – strkol 2012-03-20 12:54:52

回答

9

OK,这里是你的代码(顺便说一句,感谢张贴这样一个有趣和具有挑战性的问题 - 至少对我来说... :-)) - 使用递归对所有可能的排列(由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),你就可以得到正是你想要的东西......

+0

非常感谢你,只是我需要,谢谢:) – Minion 2012-03-20 13:24:31

+0

@MySelf不客气! :-) – 2012-03-20 13:25:48

+0

我想将其转换为返回一个数组的数组而不是一个字符串数组。所以每个内部数组都会有$ n个元素。这似乎比它看起来更难...... – 2016-10-13 23:03:44

0

您当前的代码给你排列,只需添加重复:

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

什么问题?

+0

问题是,这是非通用的,并且如果您正在处理多于2个维度,则不起作用:在3维中,他将需要添加 猫猫鱼,猫鱼猫,鱼猫猫。等等......再次组合。 – 2016-01-16 17:54:20