Heim >Backend-Entwicklung >PHP-Tutorial >PHP N选M算法 大数组打印不出来
function Combination($sort, $num){ $result = $data = array(); if( $num == 1 ) { return $sort; } foreach( $sort as $k=>$v ) { unset($sort[$k]); $data = Combination($sort,$num-1); foreach($data as $row) { $result[] = $v.','.$row; } } return $result;}$starttime = explode(' ',microtime());$arr = array(1,2,3,4,5,6,7,8,9,1,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33);//这个是组合$res = Combination($arr,6);print_r($res);$endtime = explode(' ',microtime());$thistime = $endtime[0]+$endtime[1]-($starttime[0]+$starttime[1]);$thistime = round($thistime,3);echo "本网页执行耗时:".$thistime." 秒";
打开 php 的错误显示功能,你会看到 Fatal error: Allowed memory size of ...... 这样的错误
内存不够了!
考虑是给php分配的内存不够用,ini_set('memory_limit','500M')试下
不知道我理解的对不对
N选M,如果允许重复值,每次调用随机数键名对应的值就好
如果不允许重复值,使用shuffle()函数随机排列,然后直接取前M个元素