search
HomeBackend DevelopmentPHP TutorialPHP implements random elimination algorithm

This time I will bring you PHP to implement the random elimination algorithm. What are the precautions for PHP to implement the random elimination algorithm? The following is a practical case, let's take a look.

<?php
function getKingMokey($n, $m)
{
    $monkey[0] = 0;
    //将1-n只猴子顺序编号 入数组中
    for($i= 1; $i<= $n; $i++)
    {
        $monkey[$i] = $i;
    }
    $len = count($monkey);
    //循环遍历数组元素(猴子编号)
    for($i= 0; $i< $len; $i= $i)
    {
       $num = 0;
       foreach($monkey as $key => $value)
       {
        if($value == 0) continue;
        $num++;
        $values = $value;
       }
       //若只剩一只猴子 则输出该猴子编号(数组元素值) 并退出循环
       if($num == 1)
       {
          echo $values;
          exit;
       }
       //将第$i只猴子踢出队伍(相应数组位置元素值设为0)
       $monkey[$i] = 0;
       //打印该猴子位置
       echo $i."";
       //设置计数器
       for($j= 1; $j<= $m; $j++)
       {
          //猴子编号加一,遍历下一只猴子
          $i++;
          //若该猴子未被踢出队伍,获取下一只猴子编号
          if($monkey[$i] > 0) continue;
          //若元素值为0,则猴子已被踢出队伍,进而循环取下一只猴子编号
          if($monkey[$i] == 0)
          {
              //取下一只猴子编号
              for($k= $i; $k< $len; $k++)
              {
                  //值为0,编号加1
                  if($monkey[$k] == 0) $i++;
                  //否则,编号已取得,退出
                  if($monkey[$k] > 0) break;
              }
          }
          //若编号大于猴子个数,则从第0只猴子开始遍历(数组指针归零)
          //步骤同上
          if($i == $len) $i = 0;
          //同上步骤,获取下一只猴子编号
          if($monkey[$i] == 0)
          {
             for($k= $i; $k< $len; $k++)
             {
                  if($monkey[$k] == 0) $i++;
                 if($monkey[$k] > 0) break;
             }
          }
      }
   }
}
//猴子个数
$n = 10;
//踢出队伍的编号间隔值
$m = 3;
//调用猴王获取函数
getKingMokey($n, $m);
?>

Running result:

036927185104

##Using recursive algorithm

$monkeys = array(1 , 2 , 3 , 4 , 5 , 6 , 7, 8 , 9 , 10); //monkey的编号
$m = 4; //数到第几只的那只猴子被踢出去
function killMonkey($monkeys , $m , $current = 0){
  $number = count($monkeys);
    $num = 1;
    if(count($monkeys) == 1){
      echo $monkeys[0]."成为猴王了";
      return;
    }
    else{
      while($num++ < $m){
          $current++ ;
          $current = $current%$number;
        }
        echo $monkeys[$current]."的猴子被踢掉了<br/>";
        array_splice($monkeys , $current , 1);
        killMonkey($monkeys , $m , $current);
    }
}
killMonkey($monkeys , $m);

Running result:

4的猴子被踢掉了
8的猴子被踢掉了
2的猴子被踢掉了
7的猴子被踢掉了
3的猴子被踢掉了
10的猴子被踢掉了
9的猴子被踢掉了
1的猴子被踢掉了
6的猴子被踢掉了
5成为猴王了
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of automatic loading of Yii2 framework classes

Detailed explanation of PHP implementation of parsing xml into an array case

The above is the detailed content of PHP implements random elimination algorithm. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools