// 1. sheep produce next generation on 2th and 4th year
// 2. sheep dies on 5th year
// 3. calculate total amount on certain year
var sheepfold = [],
index = 0,
amount;
function Sheep() {
this.age = 1;
this.index = index++;
}
Sheep.prototype.grow = function() {
this.age += 1;
if(/2|4/.test(this.age)) {
sheepfold.push(new Sheep());
} else if(this.age === 5) {
for(var i = 0; i < sheepfold.length; i++) {
if(this.index === sheepfold[i].index) {
sheepfold.splice(i, 1);
break;
}
}
}
}
function calc(year) {
if(!year || year < 1) return;
for (var i = 1; i <= +year; i++) {
if(i === 1) {
sheepfold.push(new Sheep());
} else {
sheepfold.forEach(function(sheep) {
sheep.grow();
});
}
}
return sheepfold.length;
}
amount = calc(20);
console.log(‘Total amount: ‘ + amount);
?
原文:http://yanzhihong23.iteye.com/blog/2286019