【问题标题】:Maximum executiontime exceeded when printing array打印数组时超出最大执行时间
【发布时间】:2018-06-08 12:06:03
【问题描述】:

我有以下代码,它打印给定数字的所有组合。当$numbers 包含两个相等的数字时,它会返回一个致命错误。

我收到以下错误:

Fatal error: Maximum execution time of 30 seconds exceeded in
C:/Apache24/htdocs/index.php on line 18

我的代码:

<?php
$numbers = array("2","1","4");
$numberofelements = count($numbers);
$factorial = 1;
for ($i=1; $i<=$numberofelements; $i++)
{
         $factorial *= $i;
}
$quantitycombinations = $factorial;
$numbersdrawn = array();
while(true)
{
    $exists = false;
    $numberdrawn1 = "";
    shuffle($numbers);
    $numberdrawn1 = implode("", $numbers);
    strval($numberdrawn1);
    foreach ($numbersdrawn as $value) {
            if(strval($value)==$numberdrawn1)
            {
                $exists = true;
            }
        }
    if(!$exists){
        array_push($numbersdrawn, $numberdrawn1);
        if(count($numbersdrawn)==$quantitycombinations)
        {
            foreach($numbersdrawn as $item)
            {
                echo $item."<br>";          
            }
            break;
        }
    }
}
?>

【问题讨论】:

  • 您的基本算法是:生成一个随机尝试,直到找到一个新尝试,然后在创建完所有尝试后,将它们显示在列表中。问题是,对于任何重复的数字,您永远不会达到组合的数量,因为它们不是唯一的。这不是你可以用蛮力解决的问题,除非你更聪明地计算总组合的数量。
  • 请参阅this question 了解一些替代方法。

标签: php arrays fatal-error


【解决方案1】:

直到$numbersdrawn 中的组合数等于$factorialwhile 循环才会停止。但是当有重复时,没有那么多不同的组合,因为有些组合是相同的。

例如如果数字为 1、2、3,则组合为 123、132、213、231、312、321。

但如果数字是 1、2、2,则组合只有 122、212、221。

你需要将$factorial除以重复元素的数量得到$quantitycombinations

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-04
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    相关资源
    最近更新 更多