php 從m個數中取n個數組合,超出記憶體怎麼辦?

來源:互聯網
上載者:User
下面是我網上找到的代碼:

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有幾百個元素,執行後超出記憶體,請問該怎麼辦?有沒有人能幫忙改進下組合的函數,我這方面很弱,不知道怎麼做?

那就不要存啊,產生一個輸出一個便可以了

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.