The PHP implementation of the Joseph ring problem USES PHP array internal Pointers to manipulate functions

  • 2020-03-31 21:10:06
  • OfStack

Take a look at the problem in more detail:
The view sourceprint? A group of monkeys in a circle, press 1,2... Number n in turn. Then count from the first one to the MTH one, kick it out of the circle, count from the back of it, count to the MTH one, kick it out... "And so on and on until at last there was only one monkey left, and that monkey was called the king. The program is required to simulate this process, input m, n, output the number of the last king.
Initially conceived when want to use PHP arrays to achieve (of course, finally using array), and then simulate the internal pointer to an array, found that want to simulate a "array pointer" is not so easy, because involves a lot of "pointer" operation, finally suddenly thought of, PHP array is itself has the internal pointer to, why go to the "build car wheels"? ! So ~ look at the code:
 
function getKingMonkey($n, $m) 
{ 
$a = array();//Declare internal array
for($i = 1; $i <= $n; $i ++) 
{ 
$a[$i] = $i;//This step is the matching of seats
} 
reset($a);//To be precise, let's use the reset() function, which can also be omitted
while(count($a) > 1)//The main loop starts, and the check condition here is to stop the loop when the number of elements in the array is equal to 1
{ 
for($counter = 1; $counter <= $m; $counter++)//A nested for loop to "kick out" monkeys that count 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 remove the array elements
} 
} 
else//If there is no next element
{ 
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, delete the array element with unset(), notice that this is end()
reset($a);//Remember to "put" the pointer inside the array
} 
} 
} 
} 
return current($a); 
} 

Test it out:
Echo "the number of Monkey King is:". GetKingMonkey (100, 17);
The output is:
The view sourceprint? The number of Monkey King is: 53
The End ~

Related articles: