JavaScript - 生成6个随机百分比,最多可达100个

问题描述 投票:3回答:4

我希望生成6个随机百分比,在JavaScript中加起来为100。我不希望最大和最小百分比之间的差异超过20%。

这样做最有效的方法是什么?

非常感谢。

javascript random numbers percentage
4个回答
2
投票

我遇到了类似的问题。关于这一点的一个好处是,不仅数字是随机的,而且数组中最大的项也是随机的,因为数组已被洗牌。

否则,大多数时候第一个数字将是最大的,第二个数字将是第二个数字等。

另一件好事是,这将生成任意数量的细分,您可以获得最大细分市场的上限。例如如果你想增加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>

0
投票

这是部分解决方案:

function get_6_rands() {
    var rands = [], rand, total = 0, normalized_rands = [];
    for (var i = 0; i < 6; i += 1) {
        rand = Math.random();
        rands.push(rand);
        total += rand;
    }
    for (var i = 0; i < 6; i += 1) {
        rand = rands[i] / total;
        normalized_rands.push(rand);
    }
    return normalized_rands;
}

function_is_valid(attempt) {
    return true; // implement `is_valid` yourself
}
do {
    var attempt = get_6_rands();
} while (is_valid(attempt) === false);
console.log(attempt); // success!

该函数将生成6个随机数,它们一起是1。它是通过规范化实现的。如果你想要整数(而不是浮点数),你需要做一些聪明的事情,只是舍入是不够的。

您可以通过检查要求获得20%要求,如果失败,请再试一次,并继续尝试,直到您得到满足您要求的要求。你最终应该得到一个,毕竟它是随机的。


0
投票

首先,你创建一个100到120之间的随机数数组:

var arPercentages = [];

for(var i = 0; i < 6; i++) {
    arPercentages.push(Math.random()*20 + 100);
}

然后添加所有数字。选择你的方法,我总是用户下划线,所以我会map()。但基本上,你要做的就是这样:

var total = arPercentages[0] + arPercentages[1] + arPercentages[2] + arPercentages[3] + arPercentages[4] + arPercentages[5];

最后,您只需对每个数字进行除法和乘法运算:

for (var i = 0; i < 6; i++) {
    arPercentages[i] = arPercentages[i] / total * 100;
}

你有一个6%的数组,增加到100,基数值的100到120%(但这非常接近)


0
投票

我不得不解决类似的问题。我就是这样做的:

const random = (min, max) => {
    return min + Math.random() * (max - min);
};

const randomFill = (amount, min, max) => {
    const arr = [];
    let total = 0;

    // fill an array with random numbers
    for (let i = 0; i < amount; i++) arr.push(random(min, max));

    // add up all the numbers
    for (let i = 0; i < amount; i++) total += arr[i];

    // normalise so numbers add up to 1
    for (let i = 0; i < amount; i++) arr[i] /= total;

    return arr;
};

minmax可以是任何东西。实际值并不重要,因为总数是标准化的。

const values = randomFill(6, 0.2, 0.5);
// [0.1549, 0.2023, 0.1681, 0.0981, 0.1621, 0.2141]

这是一个jsfiddle:https://jsfiddle.net/brunoimbrizi/q3fLp8u5/27/

© www.soinside.com 2019 - 2024. All rights reserved.