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