Home >php教程 >php手册 >php解决约瑟夫环示例

php解决约瑟夫环示例

WBOY
WBOYOriginal
2016-06-06 20:23:301292browse

这篇文章主要介绍了php解决约瑟夫环示例,需要的朋友可以参考下

约瑟夫问题(有时也称为约瑟夫斯置换,,是一个出现在计算机科学和数学中的问题。在计算机编程的算法中,类似问题又称为约瑟夫环。又称“丢手绢问题”.)

猴子一群,都带着号码的,站好了一圈,数到m的枪毙,剩下的接着数。如此往复,死剩下的一个就疯了

复制代码 代码如下:


function killMonkeys($monkeys, $m){
    $k = $m;
    while (count($monkeys)){
        $k = $k - 1;
        $monkey = array_shift($monkeys);
        if ($k) {
           $monkeys[] = $monkey;
        } else {
            echo "" . $monkey . "号猴子毙了!
";
            $k = $m;
        }

    }
    echo $monkey . "号猴子斯巴达了";
}
$monkeys = range(0, 25);
unset($monkeys['0']);
$m = 5;
killMonkeys($monkeys, $m);

Statement:
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