PHP implementation of monkey choice King problem algorithm example, Monkey King
In this paper, we describe the algorithm of PHP to implement the monkey Choice King. Share to everyone for your reference. The specific analysis is as follows:
First, the question:
N Monkeys sit in a circle, numbered from 1 to n clockwise.
Then from the 1th monkey began to count in the clockwise direction from 1, reporting m of the monkeys out, and then from the first out of the monkey's next position to restart the count,
So repeat until one of the monkeys is left, and it is the king.
Design and write programs to achieve the following functions:
(1) required by the user input at the beginning of the number of monkeys $n, count the last number of $m.
(2) Give the initial number of the chosen Monkey King.
Second, the solution:
/** * @param int $n at the beginning of the number of monkeys * @param int $m The last number reported * (Registration of the number of monkeys are eliminated, and then the next monkey starts off ①) * @return int Monkey's initial number */function mo Nkeyselectking ($n, $m) {//The initial number of monkeys cannot be less than 2 if ($n <2) {return false;} $arr =range (1, $n); Divide the monkey into an array, the value of the array corresponds to the initial number of the monkey $unsetNum = 0; Define a variable, record the monkey's count for ($i = 2; $i <= $n * $m; $i + +)//total number of cycles do not know how to calculate, {//But because return is set in the loop, $m* $len efficiency can also be foreach ($arr as $k = + $v) {$unsetNum + +;//every Monkey, monkey count +1//When the monkey's count is equal to the elimination of the number: the elimination of monkeys (delete array elements)//0 (the next monkey starting from 1) if ($unsetNum = = $m) {// echo "///Open the note, you can see the specific elimination process// Print_r ($arr); Unset ($arr [$k]); Eliminate monkeys $unsetNum = 0;// Count back zero if ($arr) ==1)//Determine the length of the array, if only one monkey is left, return its value { return reset ($arr); } } } }} var_dump (Monkeyselectking (6, 3));
Supplemental Improvement algorithm (this 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));
It is hoped that this article will be helpful to the design of PHP programming algorithm for everyone.
http://www.bkjia.com/PHPjc/987253.html www.bkjia.com true http://www.bkjia.com/PHPjc/987253.html techarticle PHP Implementation of the monkey choice King problem algorithm example, Monkey King This article describes the PHP implementation of the monkey Choice King problem algorithm. Share to everyone for your reference. The specific analysis is as follows: First, ask ...