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 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['key']]); //删除报数为3的键、值 } } if(!current($arr))reset($arr); //循环过后,因为each操作,内部指针有可能超越了数组末端,需要重置 return current($arr); } echo fun(5,3); ?>
Copyright statement: This article is an original article by the blogger and may not be reproduced without the permission of the blogger.
The above has introduced the monkey counting problem, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.