2014-12-06 64 views
-1

我有一個數組:PHP列表數組的元素的所有組合

$arr=array("A","B","C"); 

我要讓所有的組合爲:

array("A") 
array("B") 
array("C") 
array("A","B") 
array("A","C") 
array("B","C") 
array("A","B","C") 

我想打一個過程所有這些組合但我不想生成所有組合,將它們存儲在數組中並將函數應用於它們。因爲這需要大量的內存和大量的組合。我有40項這個過程(我有很長的時間,但我沒有足夠的記憶)。

我想有這樣的功能:

function ProcessArrayCombinations($array){ 
foreach($array as $v){ 
//generate and process next combination of array 
print_r($nextcombination); 
} 
} 

謝謝。

回答

1

此代碼將組合識別爲二進制數,使用的事實是存在formula這一事實,即表示可能來自n個元素的所有組合的總和爲2^n。知道它的二進制對數是整數,我們可以定義一個模型,其中由n個數字構成的每個可能的二進制數是一組組合。代碼未經測試,如果有錯別字,請在評論中告知我。

function ProcessArrayCombinations($array) { 
    $status = array(); 
    foreach ($array as $element) { 
     $status[] = false; 
    } 

    $elementCount = count($status); 
    $trues = 0; 

    while ($trues < $elementCount) { 
     $index = 0; 
     $stop = false; 
     while ((!$stop) && ($index < count($status)) && ($status[$index])) { 
      $status[$index] = false; 
      $trues--; 
      $index++; 
     } 
     $status[$index] = true; 
     $trues++; 
     //Found a new combination 
     //We should print elements from $array located at indexes fulfilling 
     //the criteria that the element having the same index in $status is true: 
     //for ($i = 0; $i < count($status); $i++) { 
     // if ($status[$i}) { 
     //  print 
     // } else { 
     //  don't print 
     // } 
     //} 
    } 
} 
+0

謝謝你的回覆,但我不明白我怎麼能打印創建的組合:/ – 2014-12-06 16:28:47

+1

我找到了它;謝謝。這解決了我的要求。但是你可以改變$ status.length來計數($ status)i ++到$ i ++和$ status.length來再次計數($ status)。 – 2014-12-06 16:40:31

+0

確實,代碼未經測試。我已經添加了您提出的修復程序。 – 2014-12-06 17:48:50

0

我編輯和使用你的功能如下。再次感謝拉霍斯。

function ProcessArrayCombinations($array) { 
    $status = array(); 
    foreach ($array as $element) { 
     $status[] = false; 
    } 

    $elementCount = count($status); 
    $trues = 0; 

    while ($trues < $elementCount) { 
     $index = 0; 
     $stop = false; 
     while ((!$stop) && ($index < count($status)) && ($status[$index])) { 
      $status[$index] = false; 
      $trues--; 
      $index++; 
     } 
     $status[$index] = true; 
     $trues++; 
     //Found a new combination 
     //We should print elements from $array located at indexes fulfilling 
     //the criteria that the element having the same index in $status is true: 
     for ($i = 0; $i < count($status); $i++) { 
      if ($status[$i]) { 
       echo $array[$i]; 
      } 
     } 
echo '<br/>'; 
    } 
}