我有一个数组:
$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);
}
}
谢谢。
此代码将组合识别为二进制数,使用这样一个事实:有一个公式指出 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
// }
//}
}
}
我编辑并使用了您的函数,如下所示。再次感谢拉约什。
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/>';
}
}