我希望在 JavaScript 中生成 6 个加起来为 100 的随机百分比。我不希望最大百分比和最小百分比之间的差异超过 20%。
最有效的方法是什么?
非常感谢。
最佳答案
我遇到了类似的问题。这样做的一个好处是,不仅数字是随机的,而且数组中最大的项目也是随机的,因为数组已被打乱。
否则,大多数情况下,第一个数将是最大的,第二个数将是第二大的,依此类推。
另一个好处是,这将根据需要生成任意数量的段,并且您可以为最大段设置上限。例如如果你想加起来等于 100,你的第一个数字不会是 99.9。
var generateProportion = function() {
var max = 100,
segmentMax = 60,
tempResults = [],
remaining = max,
segments = 5,
finalResults = [];
//create a series of random numbers and push them into an array
for (var i = 1; i <= segments; i++) {
var r = Math.random() * segmentMax;
if (i === segments) {
// the final segment is just what's left after the other randoms are added up
r = remaining;
}
tempResults.push(r);
// subtract them from the total
remaining -= r;
// no segment can be larger than what's remaining
segmentMax = remaining;
}
//randomly shuffle the array into a new array
while (tempResults.length > 0) {
var index = Math.floor(Math.random() * tempResults.length);
finalResults = finalResults.concat(tempResults.splice(index, 1));
}
return finalResults;
}
var proportion = generateProportion();
var total = proportion.reduce( (a,b) => a+b);
console.log(proportion, "=", total);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
关于JavaScript - 生成 6 个加起来为 100 的随机百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18662125/