0%

随机数求和

题设:生成 N 个随机正整数,使他们的和等于某个数。JS 实现了一下,记录之:

// 绑定表单,点击后给出计算结果
document.addEventListener('DOMContentLoaded', function(e){
  var elForm = document.getElementById('form'),
  elResult = document.getElementById('result');
  elForm.addEventListener('submit', function(e){
    e.preventDefault();
    var self = this,
    total = self\['Total'\].value,
    num = self\['Number'\].value,
    min = self\['Min'\].value,
    app = new Random(num, total, min),
    result = app.run();
    elResult.innerHTML = 'Result:   
' \+ result.join(', ');
  }, false);
}, false);

// 计算类
var Random = function(num, total, min){
  this.total = parseInt(total) || 100;
  this.num = parseInt(num) || 1;
  this.min = parseInt(min) || 0;
  this.result = \[\];
};
Random.prototype = {
  // 生成一个随机数
  random : function(t) {
    var max = t,
    min = this.min;
    return Math.floor(Math.random() * (max-min)) + min;
  },
  // 递归计算
  calc : function(t){
    var self = this,
    num = self.num,
    min = this.min;
    if(num * min > self.total){
      return this.result = \['The total number is not enough.'\];
    }
    if(num === 0){
      return false;
    }
    if(num === 1){
      self.result.push(self.total);
    }
    if(num > 1){
      var t =  self.total - (num-1)*min;
      r = self.random(t),
      self.result.push(r);
      self.total -= r;
    }
    self.num--;
    self.calc();
  },
  // 开始计算
  run : function(){
    this.calc();
    return this.result;
  }
};

点击查看 DEMO备用地址) | 源码调试