当前位置:Gxlcms > PHP教程 > phpFOR循环优化有关问题

phpFOR循环优化有关问题

时间:2021-07-01 10:21:17 帮助过:16人阅读

php FOR 循环优化问题
上次发个帖子没人跟,可能是问题不具体或者php基础编程人少或者太忙.............

我想从1-33选出6个不重复的号,然后写入数据库
现在选号过程PHP处理的很慢还总出错误,谁有兴趣帮我把下面的代码优化下:
PHP code
";//显示效果,本想写入TXT文档在传如数据库.
                    }
                }
            }
        }
    }
}
?>


------解决方案--------------------
PHP code
$a  = range(1, 33);
$ar = combination($a, 6);

//求组合高效率的10移动法
function combination($numArr,$combineLen) {
  $numCt    = count($numArr);
  if($combineLen > $numCt) return;
  $bin    = str_pad('',$combineLen,'1');
  $bin    = str_pad($bin,$numCt,'0',STR_PAD_RIGHT);    
  $find    = $bin;
  $rs[]    = implode(' ',array_slice($numArr,0,$combineLen));
  $j        = 1;
  while(strrev($find) != $bin) {
    $k = explode('10',$find,2);
    $find = $find{0} === '0' ? strrev($k[0]).'01'.$k[1] : $k[0].'01'.$k[1];
    for($i=0;$i<$numCt;$i++) $rs[$j] .=  $find[$i] ?  $numArr[$i] . " " : '';
    $j++;
  }
  return $rs;
}

------解决方案--------------------
PHP code
[User:root Time:21:21:46 Path:/home/liangdong/php]$ php permutation.php 
Total time used : 9738642ms
[User:root Time:21:21:56 Path:/home/liangdong/php]$ cat permutation.php 
= $total; ++ $ndx) {
                $temp[$num] = $table[$ndx];
                _get_permutations($ndx + 1, $num + 1);
        }
}

function get_permutations($n = 6) {
        global $total;
        global $perms;
        global $fp;

        if ($n <= 0 && $n > 33) {
                return false;
        }

        $total = $n;
        $fp = fopen("data.txt", "w");
        _get_permutations(0, 0);
        fclose($fp);
        return true;
}

get_permutations();

$end_time = microtime(true);
$end_time *= 1000 * 1000;
echo "Total time used : " . ($end_time - $beg_time) . "ms" . PHP_EOL;

?>                     

人气教程排行