Take a look at the detailed description of this question:
View Sourceprint? A group of monkeys in a circle, according to the,..., n sequentially numbered. Then, starting from the 1th, Count to M., Kick It Out of the loop, start counting from behind it, Count to M., and Kick It out ... and so on, until the last monkey is left, the monkey is called the King. Requires programming to simulate this process, enter M, N, and output the number of the last king.
At the beginning of the idea to use the PHP array to implement (of course, the final use of the array), and then simulate an array of internal pointers, the results found that it is not so easy to simulate an "array pointer", because it involves a lot of "pointer" operation, and finally suddenly think that the PHP array itself is an internal pointer, Why do you want to "build the wheel"?! So ~ look at the code:
Copy CodeThe code is as follows:
function Getkingmonkey ($n, $m)
{
$a = array ();//Declaration Internal Array
for ($i = 1; $i <= $n; $i + +)
{
$a [$i] = $i;//This step is to be
}
Reset ($a);//For the sake of rigor, let's take a reset () function, but you can also save
while (count ($a) > 1)//start of the main loop, the discriminant condition used here is that the number of array elements equals 1 stops the loop
{
for ($counter = 1; $counter <= $m; $counter + +)//nested for loop, used to "kick" the number of monkeys to M
{
if (next ($a)) {//If there is a next element
if ($counter = = $m)
{
unset ($a [Array_search (prev ($a), $a)]);//When you count to M, use unset () to delete an array element
}
}
else//If there is no next element
{
Reset ($a);//The first element of the array acts as a next element
if ($counter = = $m)
{
unset ($a [Array_search ($a), $a)]);//When you count to M, use unset () to delete the array element, note that this is the end ()
Reset ($a);//Remember to have the internal pointer of the array "homing"
}
}
}
}
return current ($a);
}
Test the following:
echo "Monkey King's number is:". Getkingmonkey (100, 17);
The output is:
View Sourceprint? Monkey King's number: 53
The end~
http://www.bkjia.com/PHPjc/322540.html www.bkjia.com true http://www.bkjia.com/PHPjc/322540.html techarticle take a look at the detailed description of this question: View Sourceprint? A group of monkeys in a circle, according to the,..., n sequentially numbered. Then starting from the 1th number, count to the number of M only, kick It out of the loop, from it ...