Home > Backend Development > PHP Tutorial > php monkey chooses the king

php monkey chooses the king

WBOY
Release: 2016-08-08 09:26:44
Original
1908 people have browsed it

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
Copy after login

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));
Copy after login


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
Copy after login


The above introduces the PHP Monkey King, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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