目錄
php 从m个数中取n个数组合,超出内存怎么办?
Jun 06, 2016 pm 08:24 PM
php
下面是我网上找到的代码:
<code>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; } </code>
登入後複製
登入後複製
<code>$arr=['a','b','c','d','e','f']; getCombinationToString($arr,3);</code>
登入後複製
登入後複製
输出结果:
Array
(
<code>[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</code>
登入後複製
登入後複製
)
现在我的$arr有几百个元素,执行后超出内存,请问该怎么办?有没有人能帮忙改进下组合的函数,我这方面很弱,不知道怎么做?
回复内容:
下面是我网上找到的代码:
<code>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; } </code>
登入後複製
登入後複製
<code>$arr=['a','b','c','d','e','f']; getCombinationToString($arr,3);</code>
登入後複製
登入後複製
输出结果:
Array
(
<code>[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</code>
登入後複製
登入後複製
)
现在我的$arr有几百个元素,执行后超出内存,请问该怎么办?有没有人能帮忙改进下组合的函数,我这方面很弱,不知道怎么做?
那就不要存啊,生成一个输出一个便可以了
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章
擊敗分裂小說需要多長時間?
3 週前
By DDD
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

適用於 Ubuntu 和 Debian 的 PHP 8.4 安裝和升級指南

如何設定 Visual Studio Code (VS Code) 進行 PHP 開發
