This article introduces the PHP version of the Joseph Ring problem (monkey chooses the king). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Joseph Ring Problem (Monkey Chooses the King) PHP Version
The Josephus Problem is sometimes described as the monkey chooses the king problem, and the title is as follows. (The origin of Joseph's question will be posted at the end)
A group of monkeys line up in a circle and are numbered according to 1, 2,...,n.
Then start counting from the 1st one, count to the mth one, kick it out of the circle, start counting from behind it, count to the mth one again, kick it out..., and so on. This continues until there is only one monkey left, and that monkey is called the king.
Requires programming to simulate this process, input m, n, and output the number of the last king.
Use a program to simulate this process. The code is as follows:
function monkeyKing($n, $m) { $arr = range(1, $n); //构造一个数组 $i = 1; //从第一个开始循环 while (count($arr) > 1) { //如果总数大于1 if ($i % $m != 0) { $arr[] = $arr[$i - 1]; //不被踢出则压入数组尾部 } unset($arr[$i - 1]); //压入数组然后删除 $i++; //继续循环 } return $arr[$i - 1]; //直至最后剩下一个为大王 } print_r(monkeyKing(5, 3)); //第4只为大王
The following is the simulation process. For monkeys that are not eliminated, the tail of the array is continuously added:
$n = 5 $m = 3 $arr = [1, 2, 3, 4, 5] $i $arr ---+------------------------ 1 x 2 3 4 5 1 2 x x 3 4 5 1 2 >3 x x x 4 5 1 2 4 x x x x 5 1 2 4 5 x x x x x 1 2 4 5 >6 x x x x x x 2 4 5 7 x x x x x x x 4 5 2 8 x x x x x x x x 5 2 4 >9 x x x x x x x x x 2 4 10 x x x x x x x x x x 4 2 11 x x x x x x x x x x x 2 4 >12 x x x x x x x x x x x x 4
The origin of Joseph's problem :
This question is named after Flavio Josephus, a 1st century Jewish historian. He wrote in his diary that he and 40 of his comrades were surrounded by Roman troops in the cave. They discussed whether to commit suicide or be captured, and finally decided to commit suicide, and decided who would kill whom by drawing lots. Josephus and one other man were the last two left. Josephus convinced the man that they would surrender to the Roman army and not commit suicide again. Josephus attributed his survival to luck or providence, he did not know which.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of One article to solve the Joseph ring problem (PHP version). For more information, please follow other related articles on the PHP Chinese website!

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

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.

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

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

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

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.

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6
Visual web development tools
