below for you to introduce the implementation of PHP Monkey selection algorithm example.
This article is an example of the implementation of the PHP Monkey selection algorithm. Share to everyone for your reference. The specific analysis is as follows:
First, the question:
N Monkeys are seated in a circle, numbered clockwise from 1 to N.
Then from the 1th Monkey began to start off in the clockwise direction from 1, Report M's monkey out, and then from just out of the monkey's next position to start off again,
So repeat, until a monkey is left, it is the king.
Design and write programs to achieve the following functions:
(1) Require the user to enter the beginning of the number of monkeys $n, count the last number of $m.
(2) Give the initial number of the selected Monkey King.
Second, the solution:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 This is the |
; >/** * @param int $n The number of monkeys at the beginning * @param int $m The last number of reports * (report on this number of monkeys was eliminated, and then the next monkey starts off the ①) * @return The initial number of the int monkey/function m Onkeyselectking ($n, $m) {//Monkey's initial number must not be less than 2 if ($n <2) {return false;} $arr =range (1, $n);//////////////////////////////// Number $unsetNum = 0; Define a variable to record the monkey's count off for ($i = 2; $i <= $n * $m; $i + +)//The total number of cycles does not know how to calculate, {//But because the loop is set return, so $m* $len efficiency can also foreach ($ Arr as $k => $v) {$unsetNum + +//////////////////////////////////////////////////////////// = $m) {//echo "<pre>";//Open comment, you can see the specific elimination process//Print_r ($arr); unset ($arr [$k]);//Eliminate Monkey $unsetNum = 0;//Count to zero if ($a RR)//To determine the length of the array, if only one monkey is left, return its value {returns reset ($arr);} ==1 }} Var_dump (Monkeyselectking (6, 3)); |
Additional improved algorithm (the algorithm is more concise and clear!) :
?
1 2 3 4 5 6 7 8 9 |
function Yuesefu ($n, $m) {$r =0; for ($i =2; $i <= $n; $i + +) {$r = ($r + $m)% $i;} return $r +1;} print_r (Yuesefu (3,3)); |
I hope this article will help you with the design of PHP program algorithm.