欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php 从m个数中取n个数组合,超出内存怎么办?

程序员文章站 2022-05-23 15:11:59
...
下面是我网上找到的代码:
function getCombinationToString($arr,$m)
{
    $result = array();
    if ($m ==1)
    {
        return $arr;
    }

    if ($m == count($arr))
    {
        $result[] = implode(',' , $arr);
        return $result;
    }

    $temp_firstelement = $arr[0];
    unset($arr[0]);
    $arr = array_values($arr);
    $temp_list1 = getCombinationToString($arr, ($m-1));

    foreach ($temp_list1 as $s)
    {
        $s = $temp_firstelement.','.$s;
        $result[] = $s;
    }
    unset($temp_list1);

    $temp_list2 = getCombinationToString($arr, $m);
    foreach ($temp_list2 as $s)
    {
        $result[] = $s;
    }
    unset($temp_list2);

    return $result;
}
$arr=['a','b','c','d','e','f'];
getCombinationToString($arr,3);

输出结果:

Array
(

[0] => a,b,c
[1] => a,b,d
[2] => a,b,e
[3] => a,b,f
[4] => a,c,d
[5] => a,c,e
[6] => a,c,f
[7] => a,d,e
[8] => a,d,f
[9] => a,e,f
[10] => b,c,d
[11] => b,c,e
[12] => b,c,f
[13] => b,d,e
[14] => b,d,f
[15] => b,e,f
[16] => c,d,e
[17] => c,d,f
[18] => c,e,f
[19] => d,e,f

)
现在我的$arr有几百个元素,执行后超出内存,请问该怎么办?有没有人能帮忙改进下组合的函数,我这方面很弱,不知道怎么做?

回复内容:

下面是我网上找到的代码:

function getCombinationToString($arr,$m)
{
    $result = array();
    if ($m ==1)
    {
        return $arr;
    }

    if ($m == count($arr))
    {
        $result[] = implode(',' , $arr);
        return $result;
    }

    $temp_firstelement = $arr[0];
    unset($arr[0]);
    $arr = array_values($arr);
    $temp_list1 = getCombinationToString($arr, ($m-1));

    foreach ($temp_list1 as $s)
    {
        $s = $temp_firstelement.','.$s;
        $result[] = $s;
    }
    unset($temp_list1);

    $temp_list2 = getCombinationToString($arr, $m);
    foreach ($temp_list2 as $s)
    {
        $result[] = $s;
    }
    unset($temp_list2);

    return $result;
}
$arr=['a','b','c','d','e','f'];
getCombinationToString($arr,3);

输出结果:

Array
(

[0] => a,b,c
[1] => a,b,d
[2] => a,b,e
[3] => a,b,f
[4] => a,c,d
[5] => a,c,e
[6] => a,c,f
[7] => a,d,e
[8] => a,d,f
[9] => a,e,f
[10] => b,c,d
[11] => b,c,e
[12] => b,c,f
[13] => b,d,e
[14] => b,d,f
[15] => b,e,f
[16] => c,d,e
[17] => c,d,f
[18] => c,e,f
[19] => d,e,f

)
现在我的$arr有几百个元素,执行后超出内存,请问该怎么办?有没有人能帮忙改进下组合的函数,我这方面很弱,不知道怎么做?

那就不要存啊,生成一个输出一个便可以了

相关标签: php