0%

随机数求和

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// 绑定表单,点击后给出计算结果
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备用地址) | 源码调试

欢迎关注我的其它发布渠道