Take a look at the detailed description of the problem:
View Sourceprint? A group of monkeys in a circle, press 1,2,..., n sequentially numbered. And then starting from the 1th number, count to M only, kick It out of the loop, start from behind it, Count to M only, kick It out ..., keep going until the last monkey is left, the monkey is called King. Requires programming to simulate this process, input m, n, output the last king's number.
Just start thinking about using a PHP array to implement (and, of course, the last array to use), then simulate an array of internal pointers, the result found that want to simulate an "array pointer" is not so easy, because involves a lot of "pointers" operation, finally suddenly thought that the PHP array itself is an internal pointer, Why do we have to "build wheels"?! So ~ look at the code:
Copy Code code as follows:
function Getkingmonkey ($n, $m)
{
$a = array ();//Declare an internal array
for ($i = 1; $i <= $n; $i + +)
{
$a [$i] = $i;//This step is a condemnation
}
Reset ($a)//for rigorous, we have a reset () function, in fact, you can save
while (count ($a) > 1)//The main loop starts with a discriminant that stops the loop when the number of array elements equals 1.
{
for ($counter = 1; $counter <= $m; $counter + +)//nested for loop, used to "kick out" count to M's monkey
{
if (next ($a)) {//If there is a next element
if ($counter = = $m)
{
unset ($a [Array_search (prev ($a), $a)]///When the number of M is used, the element of the array is deleted using unset ()
}
}
else//if no next element exists
{
Reset ($a);//The first element of the array acts as the next element
if ($counter = = $m)
{
unset ($a [Array_search ($a), $a)]///When number to M, use unset () to delete the array element, note that this is end ()
Reset ($a);//Remember to let the array internal pointer "return"
}
}
}
}
return current ($a);
}
Test the following:
echo "Monkey King's number is:". Getkingmonkey (100, 17);
The output is:
View Sourceprint Monkey King's number is: 53
The end~