monkey counting problem

巴扎黑
Release: 2016-11-10 13:56:10
Original
1172 people have browsed it

n monkeys sit in a circle and take turns reporting 1, 2, and 3, and every monkey that reports 3 will get out of the queue. The last remaining one is the monkey king. Please write a function in php. The input is the number of monkeys and the starting position of the count. The return value is the serial number of the monkey king.

Php code

<?php  
  
function fun($n,$begin)  
{  
//输入判断  
if(!is_int($n) || $n<=0)return false;  
if(!is_int($begin) || $begin>$n || $begin<=0)return false;  
  
//初始化数组,使其内部指针指向传进函数的“开始位置”  
$arr = array();  
for($i=1;$i<=$n;$i++)$arr[] = $i;  
for($i=1;$i<$begin;$i++,next($arr));  
  
while(count($arr)>1) //当数组大小不为1时循环报数  
{  
//报数,往后数两位  
for($i=0;$i<2;$i++)  
{  
if(!next($arr))reset($arr);  
}  
//获得报数3位置的键、值(此处内部指针会前进一步)  
$key = each($arr);  
  
if(!current($arr)) //如果报数到3的位置是数组末端,及通过each后,指针超出了数组的范围  
{  
reset($arr); //将内部指针重置到数组首部  
array_pop($arr); //删除数组末端的键、值  
}  
else  
{  
prev($arr); //否则指针回退一格  
unset($arr[$key[&#39;key&#39;]]); //删除报数为3的键、值   
}  
}  
if(!current($arr))reset($arr); //循环过后,因为each操作,内部指针有可能超越了数组末端,需要重置  
return current($arr);  
}  
  
echo fun(5,3);  
?>
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template