douqiju2520 2017-12-27 21:49
浏览 75
已采纳

打印阵列时超出最大执行时间

I have the following code, which prints all combinations of the given numbers. It returns a fatal error when $numbers contains two equal numbers.

I get the following error:

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

My Code:

<?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;
        }
    }
}
?>
  • 写回答

1条回答 默认 最新

  • duanhe0817825 2017-12-27 22:03
    关注

    The while loop doesn't stop until the number of combinations in $numbersdrawn is equal to $factorial. But when there are duplicates, there aren't that many different combinations, because some of the combinations are identical to each other.

    E.g. if the numbers are 1, 2, 3, the combinations are 123, 132, 213, 231, 312, 321.

    But if the numbers are 1, 2, 2, the combinations are only 122, 212, 221.

    You need to divide $factorial by the number of repeated elements to get $quantitycombinations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来