php solve joseph ring

WBOY
Release: 2016-08-08 09:32:25
Original
1354 people have browsed it
<?php>
#编号1到n的n个猴子围成一圈,从k号猴子开始从1报数,k+1号猴子报2,k+2号猴子报3........ 报到m就出局 剩下的重新从1报数,报到m出局,反复循环, 求最后剩下的那只猴子的编号。
function myf($array,$m,$n,$k){
    $mark=0;
    $a=$m;
    $m=$m+$k-1;

    while(sizeof($array)){
    	$mark++;
    	$out=array_shift($array);
        if($mark==$m){
        	if(sizeof($array)==0){
        	echo $out , '最终留下<br/>';
        	}else{
                    $m=$a;
        	    echo $out , '出局<br/>';
        	    $mark=0;


        	}
        }else{
         $array[]=$out;
        }


    }


}

myf(range(1, 5),3,5,2);#测试一下,编号1到5的猴子,从2号开始由1报数,报到3的出局

 ?>
Copy after login

The above introduces PHP to solve the Joseph ring, 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