2014-12-06 133 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/>'; 
    } 
}