Method 1:
function monkeyKing($n,$m) { $arr=range(1,$n); $i=0; while (count($arr)>1) { for($i=1;$i<=$m-1;$i++) { array_push($arr, array_shift($arr)); } array_shift($arr); } echo "$arr[0]"; } monkeyKing(6,4);//5
Method 2:
function king($m ,$n) { //构造数组 $arr=range(1,$m); $i = 0 ; //设置数组指针 while(count($arr)>1) { //遍历数组,判断当前猴子是否为出局序号,如果是则出局,否则放到数组最后 if(($i+1)%$n ==0) { unset($arr[$i]) ; } else { array_push($arr ,$arr[$i]) ; //本轮非出局猴子放数组尾部 unset($arr[$i]) ; //删除 } $i++ ; } return $arr ; } var_dump(king(6,4));
Method 3: //I don’t understand this method very well. I hope everyone can leave their opinions.
function yuesefu($n,$m) { $r=0; for($i=2; $i<=$n; $i++) { $r=($r+$m)%$i; } return $r+1; } print_r(yuesefu(3,3));//2
The above introduces the PHP Monkey King, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.