In the previous article "PHP Random Picking One Algorithm (2)", we introduced in detail the implementation idea of ??PHP Random Picking One Algorithm, which is the "Fair Selection of Monkey King" interview question solution.
# Now we will combine the code methods in the above articles to show you the process of debugging and running the algorithm through Xdebug.
The question is as follows:
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, kick it out..., and continue in this way until the end. Until there is only one monkey left, that monkey is called the king. Programming is required to simulate this process, input m, n, and output the number of the last king.
The code is as follows:
<?php function king($n, $m){ $monkeys = range(1, $n); //創(chuàng)建1到n數(shù)組 $i=0; while (count($monkeys)>1) { //循環(huán)條件為猴子數(shù)量大于1 if(($i+1)%$m==0) { //$i為數(shù)組下標(biāo);$i+1為猴子標(biāo)號 unset($monkeys[$i]); //余數(shù)等于0表示正好第m個,刪除,用unset刪除保持下標(biāo)關(guān)系 } else { array_push($monkeys,$monkeys[$i]); //如果余數(shù)不等于0,則把數(shù)組下標(biāo)為$i的放最后,形成一個圓形結(jié)構(gòu) unset($monkeys[$i]); } $i++;//$i 循環(huán)+1,不斷把猴子刪除,或 push到數(shù)組 } return current($monkeys); //猴子數(shù)量等于1時輸出猴子標(biāo)號,得出猴王 } echo king(10,3);
First we create a breakpoint before the fourth line of code.
#Then open the browser and run this code. The breakpoint successfully obtains focus, as follows.
#Create an array from 1 to n.
Then the while loop determines whether to delete the element.
This cycle leads to the "Monkey King".
Related recommendations: "How to configure and use the xdebug tool in PHPStorm? (Picture, text and video tutorial) 》
So that’s it for the introduction of PHP’s random selection algorithm. You can also test it locally. It's actually very simple. I hope it will be helpful to friends who need it!
The above is the detailed content of PHP random selection algorithm (3). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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