Home > Article > Backend Development > Monkey chooses the king, monkey king_PHP tutorial
A group of monkeys line up in a circle and number them sequentially according to 1, 2,...,n. Then start counting from the 1st one, count to the mth one, kick it out of the circle, start counting from behind it, count to the mth one, kick it out..., and continue in this way until the end. Until there is only one monkey left, that monkey is called the king. Programming is required to simulate this process, input m, n, and output the number of the last king
//Basic idea, determine whether the monkey is out, delete it if it is, otherwise put it at the end of the data
function xdw($m, $n){
for($i = 1; $i <= $n; $i ){
$arr[] = $i;
}
for($i = 0; count($arr)>1; $i ){
if( ($i 1) % $m == 0){
unset($arr[$ i]);
}else{
array_push($arr, $arr[$i]);
unset($arr[$i]);
}
}
return $arr;
}
print_r(xdw(2,10));