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:
/**
* @param int $n The number of monkeys at the beginning
* @param int $m The last number of reports
* (report on this number of monkeys were eliminated, and then the next monkey started off the ①)
* @return int Monkey's initial series Number
*/
function monkeyselectking ($n, $m)
{
//Monkey's initial number cannot be less than 2
if ($n <2) {return
false;
}
$arr =range (1, $n);
The monkeys are divided into an array, the value of the array corresponds to the monkey's initial number
$unsetNum =0;
Define a variable, record the monkey count for
($i = 2; $i <= $n * $m; $i + +)
//Total number of cycles do not know how to calculate,
{
//But because the loop set the return, so $m*$ Len efficiency can also be
foreach ($arr as $k => $v)
{
$unsetNum + +;///Every monkey, monkey count +1
//When the number of monkeys is equal to the elimination of numbers: elimination of monkeys ( Delete array elements)
//Count to 0 (the next monkey starts from 1)
if ($unsetNum = = $m)
{
// echo "<pre>";//Open Comment, The specific phase-out process
// Print_r ($arr) can be seen;
Unset ($arr [$k]);
Elimination of monkeys
$unsetNum =0;
Number of
returns to zero if (count ($arr) ==1)
//judge the length of an array, if there is only one monkey left, return its value
{
reset ($arr);
}
}}
}
}
Var_dump (Monkeyselectking (6, 3));
Additional improved algorithm (the algorithm is more concise and clear!) ):
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.