`
yanzhihong23
  • 浏览: 59225 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Sheep Problem

阅读更多
// 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);

 

1
4
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics