Home >php教程 >PHP源码 >约瑟夫环递归和非递归解法

约瑟夫环递归和非递归解法

PHP中文网
PHP中文网Original
2016-05-25 17:09:071255browse

1.test.php

<?php
/**
 * 递归
 */
function king($arr,$n,$i)
{
    if(count($arr) == 1)
    {
        return $arr;
    }
    foreach($arr as $k=>$v)
    {
        if($i== $n)
        {
            array_shift($arr);
            $i = 1; // 重新开始
        }else
        {
            $of1 = array_shift($arr);
            array_push($arr,$of1);
            $i++;  // 指针移动
        }
        return king($arr,$n,$i);
         
    }
}
$i = 1;
$arr = array(1,2,3,4,5,6,7,8,9,10);
$king = king($arr,5,$i);
print_r($king);
// output Array ( [0] => 3 )

2.test1.php

<?php
/**
 * 循环
 */
function king($arr ,$n)
{
    $i = 0 ;   
    while(count($arr)>1)
    {
       if(($i+1)%$n ==0) 
       {
         unset($arr[$i]) ;
       } 
       else
       {
         unset($arr[$i]) ;
       }
       $i++ ;
    }
return $arr ;
}
$arr = array(1,2,3,4,5,6,7,8,9,10);
print_r(king($arr,5));
// output Array ( [45] => 3 )
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
Previous article:ThinkPHP敏感词汇过滤Next article:PHP中文文件名