Home > Backend Development > PHP Tutorial > Recursive and non-recursive algorithms for cows giving birth.

Recursive and non-recursive algorithms for cows giving birth.

WBOY
Release: 2016-08-08 09:25:37
Original
1751 people have browsed it

//一只母牛,第二年底生一只母牛和一只公牛,第三年底生一只母牛 ,第五年开始母牛会死。公牛也只能活四年。请问一个农场开始只有一只刚出生的母牛,N年后一共有多少只牛。

//请写一个函数输出结果,用递归和非递归两种方法来实现. 

function cowrecursion($i)
{
	if ($i == 1) //如果是第一年,则1头牛。 
	{
		return 1;
	}
	elseif ($i == 2)
	{
		return 2 + cowrecursion(1); //第一母牛和儿子们+第二母牛第一年		
	}
	elseif ($i == 3)
	{
		return 2 + cowrecursion(2) +  cowrecursion(1); //第一母牛和儿子们+第二母牛第二年 +第三母牛第一年
	}
	elseif ($i ==4)
	{
		return 2 + cowrecursion(3) +  cowrecursion(2);  //第一母牛和儿子们+第二母牛第三年 +第三母牛第二年
	}
	// elseif ($i == 5)
	// {		
		// return cowrecursion(4) +  cowrecursion(3);    //第一母牛死了。公牛也死了。第二母牛第四年 +第三母牛第三年		
	// }
	elseif ($i >= 5)
	{
		return cowrecursion($i-1) +  cowrecursion($i-2);  
	}
}


//非递归方式实现
function cow_norecursion($i)
{
	//实现思路,用数组来存储,value的值表示年限。循环加1.
	$cows = array(1);  //第一年,1头母牛。
	$cowsmale = array();  //用于存储公牛
	
	for ($j=0;$j<$i;$j++)  //循环多少年
	{
		//循环母牛 


		$cows_copy = $cows;
		foreach ($cows as $key => $value)
		{		
			switch($cows_copy[$key])
			{
				case 1:				
				    break;
				case 2:
				    $cows_copy[] = 1;
				    $cowsmale[] = 1;
				    break;
				case 3:
				    $cows_copy[] = 1;
				    break;
				case 4:
				
				    break;
				case 5:
				    unset($cows_copy[$key]);
				    break;
				
			}
		
		}
	
			
		$cows = $cows_copy;
		
		array_walk($cows, function(&$value, $index){
               if ($value > 0) $value++;
		 });
		
		
		
		$cowsmale_copy = $cowsmale;
	    //循环公牛
		foreach ($cowsmale as $d => $value)
		{			
		    $cowsmale_copy[$d]++;
			if ($cowsmale_copy[$d] == 5)    //到第四年就死了
			{
				unset($cowsmale_copy[$d]);
		    }			
			
		}	
         $cowsmale = $cowsmale_copy; 		
	}

	return count($cows) + count($cowsmale); 
}
echo "<br />list  totol--->".cow_norecursion(26);

echo "<br />totol  recursion--->".cowrecursion(26);
Copy after login

//end

The above introduces the recursive algorithm and non-recursive algorithm for cows to give birth. , including relevant 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