问题:一只羊的寿命是5年,在2岁和4岁的时候生育一只羊,不考虑其他情况,在N年后,羊有多少只?用面向对象的编程思想。
实现:
<?php
$sheep = new sheep(10);
print '存活:'.$sheep->exist_sheep_count().'<br>';
print '后代:'.$sheep->later_generation_count();
/**
* 羊生羊
*/
class sheep{
const LIFE = 5;
const CUR_LIFE = 0;
protected $_son = [];
public $year;
public function __construct($year){
$this->year = $year;
$this->_born();
}
protected function _born(){
$cur_life = self::CUR_LIFE;
for($cur_life<=self::LIFE && $this->year>=$cur_life;$cur_life++){
if($cur_life>0 && $cur_life%2 == 0){
$temp_year = $this->year - $cur_life;
array_push($this->_son, new sheep($temp_year));
}
}
}
protected function _exist(){
return $this->year <= self::LIFE ? 1 : 0;
}
//计算该羊的后代的数目
public function later_generation_count(){
$count = 0;
foreach ($this->_son as $one) {
$count += $one->later_generation_count();
}
return $count + count($this->_son);
}
//计算存活的羊的数目
public function exist_sheep_count(){
$count = 0;
foreach ($this->_son as $one) {
$count += $one->exist_sheep_count();
}
return $count + $this->_exist();
}
}