/*
一群猴子排成一圈,按1,2,…,n依次编号。然后从第1只开始数,数到第m只,把它踢出圈,从它后面再开始数,
再数到第m只,在把它踢出去…,如此不停的进行下去,直到最后只剩下一只猴子为止,那只猴子就叫做大王。
要求编程模拟此过程,输入m、n, 输出最后那个大王的编号。
*/
function monkey($monkey , $n , $current = 0 ){
$count = count( $monkey );
$num = 1;
if( $count == 1){
echo "猴子的编号为".$monkey[0];
return ;
}else{
while( $num++ < $n ){
$current++;
$current = $current % $count ;
}
echo "被踢出局的猴子为".$monkey[$current];
array_splice($monkey , $current , 1);
monkey( $monkey ,$n ,$current);
}
}
#array_splice #array_slice
$monkeys = array(1 , 2 , 3 , 4 , 5 , 6 ); //monkeys的编号
echo monkey( $monkeys ,4,0);
猴子选大王问题(约瑟夫环)
最新推荐文章于 2022-02-24 21:06:50 发布