码农

使用javascript计算100头随机公母牛,三年后生小牛,n

2019-08-18  本文已影响0人  潜水的旱鸭子

题干:

某农产购买了100头牛,有公有母,但是不确定公牛和母牛的数量(每头牛的性别50%随机概率),购进之后第一年起,母牛每三年会生一只小牛(小牛也不确定公母),如果是小母牛,那么每隔三年,也开始生小牛。20年后,农场共有多少只牛?(假定母牛没有任何生理和心理问题,也不考虑寿命问题)

分析:

  1. 初始100头牛的性别和年龄
  2. 母牛三年后生小牛
  3. 小牛的公母
  4. 20年

代码:

class Cattle{
    constructor(options){
        this.year = options.year; // 指定年数
        this.num = options.num;   // 初始牛数量
        this.sum = this.num;      // 初始总数
        this.cattle = [];         // 所有牛,[{age:1,sex:1}]
        this.getCattle();         // 买进100头牛,年龄为1,性别随机
        this.time();              // 时间流逝
    }
    getCattle(){    // 买进牛
        for(var i=0;i<this.num;i++){
            this.cattle.push({
                age:1,
                sex:this.getSex()
            })
        }
    }
    getSex(){      // 50%几率随机性别:0母,1公
        return Math.random()>=0.5 ? 0 : 1;
    }
    birth(){       // 生小牛
        var generation = 0;   // 当前牛是第几代
        this._num = 0;        // 统计有多少牛,要生了
        this.cattle.forEach((item)=>{
            // 判断年龄,计算有多少牛要生了
            if(item.age%3 == 0 && item.sex == 0){
                this._num++
            }
        })
        // 统一出生
        for(var i=0;i<this._num;i++){
            this.cattle.push({
                age:1,
                sex:this.getSex(),
                generation:++generation
            })
        }
    }
    time(){        // 时间流逝
        for(var i=0;i<this.year;i++){
            // 每过一年,年龄增加1,初始为1
            // 2年之后,年龄为3,开始出生
            var le = this.cattle.length;
            for(var j=0;j<le;j++){
                this.cattle[j].age++;
            }
            // 年龄增加之后,准备出生
            this.birth();
        }
        // 得到总数量
        this.sum = this.cattle.length;
    }
}
         
var c = new Cattle({
    num:100,    // 初始牛数量
    year:20     // n年之后
})

console.log(c.sum);    // 20年后牛的数量

end...


程序如有问题,或有更优化方案,欢迎留言指出,谢谢支持……^ _ ^

上一篇 下一篇

猜你喜欢

热点阅读