Home > php教程 > PHP源码 > body text

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

PHP中文网
Release: 2016-05-25 17:09:07
Original
1190 people have browsed it

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

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 )
Copy after login
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!