羊生羊

问题:一只羊的寿命是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();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值