A group of monkeys in a circle, press 1,2,..., n sequentially numbered.
And then starting from the 1th, counting to the first m, kicking it out of the loop,
Start from behind it again, count to M only, kick It out ...,
Keep on going until the last monkey is left, the monkey is called the King.
Requires programming to simulate this process, input m, n, output the last king's number.
*/
function Getkingmokey ($n, $m)
{
$monkey [0] = 0;
Numbering 1-n monkeys sequentially in an array
for ($i = 1; $i <= $n; $i + +)
{
$monkey [$i] = $i;
}
$len = count ($monkey);
Looping through array elements (monkey numbers)
for ($i = 0; $i < $len; $i = $i)
{
$num = 0;
/*
* Iterate over the $monkey array to calculate the number of elements in the array with a value of not 0 (the number of monkeys remaining)
* Assign to $num and get the element value of an element with a value of not 0
*/
foreach ($monkey as $key => $value)
{
if ($value = = 0) continue;
$num + +;
$values = $value;
}
If only one monkey is left, the monkey number (array element value) is exported and the loop is exited
if ($num = = 1)
{
Echo $values;
Exit
}
/*
* If the number of monkeys remaining is greater than 1 ($num > 1)
* Continue the program
*/
Kick the $i monkey out of the team (the corresponding array position element value is set to 0)
$monkey [$i] = 0;
Print the monkey position
echo $i. "";
/*
* Get the next monkey that needs to be kicked out of the team. Number
* traverse the monkeys within the $m value range and set $m counters
* Take a monkey number in turn
* If the element value is 0, then the position of the monkey has been kicked out of the team
* If not 0, Continue to get the next monkey number, and the counter plus 1
* If the monkey number is greater than the number of arrays
* Then go through the No. 0 Monkey (array pointer to zero) step above
* Until the counter reaches the $m value * The last $i value is the next monkey number that needs to be kicked out of the team
*/
Set up counters
for ($j = 1; $j <= $m; $j + +)
{
Monkey number plus one, traversing the next monkey
$i + +;
If the monkey is not kicked out of the team, get the next monkey number
if ($monkey [$i] > 0) continue;
If the element value is 0, the monkey has been kicked out of the team and then recycled to remove a monkey number
if ($monkey [$i] = = 0)
{
Remove a monkey number
for ($k = $i; $k < $len; $k + +)
{
Value is 0, number plus 1.
if ($monkey [$k] = = 0) $i + +;
//Otherwise, Number has been obtained, exit
if ($monkey [$k] > 0) break;
}
}
//If the number is greater than that of monkeys, begin traversing the No. 0 monkey (array pointer to zero) step above
if ($i = = $len) $i = 0;
//Previous steps, get the next monkey number
if ($monkey [$i] = = 0)
{
for ($k = $i; $k < $len; $k + +)
{
if ($monkey [$k] = = 0) $i + +;
if ($monkey [$k] > 0) break;
}
}
}
}
}
Number of monkeys
$n = 10;
Kick out the number interval value of the team
$m = 3;
Call Monkey Get function
Getkingmokey ($n, $m);
?>