<?php
#猴子数量
$total = 100;
#逢几退出选拔
$num = 7;
$monkeyArr = range(1, $total);
echo getMonkeyKing($monkeyArr, $num);
#核心算法
function getMonkeyKing($monkeyArr, $num)
{
if (!is_array($monkeyArr) || count($monkeyArr) == 0) {
return 0;
} elseif (count($monkeyArr) == 1) {
return 1;
}
$king = 0;
while (count($monkeyArr) > 1) {
foreach ($monkeyArr as $key => $val) {
if (($key + 1) % $num != 0) {
$monkeyArr[] = $val;#不是对应号的加入到数组后面
$king = $val;
}
unset($monkeyArr[$key]);#报过号的都从数组中踢出去。
}
}
return $king;
}