I believe everyone is familiar with the Joseph ring problem. I always wanted to use PHP to implement it. after a long time, I finally got it. maybe some code on the Internet is not concise and efficient, but after all, it is written ~ Haha. Let's take a look at the detailed description of this problem:
View sourceprint? A group of monkeys are arranged in a circle and numbered by 1, 2,... and n. Then start counting from 1st, count to m, kick it out of the circle, start counting from behind it, count to m, and kick it out ..., the monkey is called the King until there is only one monkey. Programming to simulate this process, input m, n, and output the number of the last king.
At the beginning, I wanted to use the PHP array to implement it (of course, the array is still used), and then simulate an internal pointer of an array, the result shows that it is not so easy to simulate an "array pointer". because many "pointer" operations are involved, the PHP array itself has an internal pointer, why do we need to create a wheel ?! Hence ~ Check the code:
The code is as follows:
Function getKingMonkey ($ n, $ m)
{
$ A = array (); // declare an internal array
For ($ I = 1; $ I <= $ n; $ I ++)
{
$ A [$ I] = $ I; // This step is the right sign.
}
Reset ($ a); // to be rigorous, we can use a reset () function to save
While (count ($ a)> 1) // The start of the main loop. the criterion used here is to stop the loop when the number of array elements is equal to 1.
{
For ($ counter = 1; $ counter <= $ m; $ counter ++) // nested for loop, used to "kick out" the monkey to m
{
If (next ($ a) {// if the next element exists
If ($ counter = $ m)
{
Unset ($ a [array_search (prev ($ a), $ a)]); // when you count to m, use unset () to delete array elements
}
}
Else // if the next element does not exist
{
Reset ($ a); // The first element of the array acts as the next element.
If ($ counter = $ m)
{
Unset ($ a [array_search (end ($ a), $ a)]); // when you count to m, use unset () to delete array elements. Note that this is end ()
Reset ($ a); // Remember to reset the internal pointer of the array"
}
}
}
}
Return current ($ );
}
Test environment:
Echo "Monkey King number:". getKingMonkey (100, 17 );
Output:
View sourceprint? Monkey King ID: 53
The End ~