Home > OS >  random number and percentage - picking value
random number and percentage - picking value

Time:11-08

I somehow need to find a solution to the problem, though, can't know exactly what and how this can be achieved.

Let's imagine I have some properties

prop1 - 7%

prop2 -3%

prop4 - 35%

and so on. those values above (7,3,35) are percentage changes of being picked.

Now, I have a random number between 0 and 1.

Can I somehow use the above information and pick the property depending on that random number and the percentages ?

how can it be possible ? sorry for my out-of-this-world question.

CodePudding user response:

You can use a random number to pick an option in a weighted list of options, whether the sum of all weightings adds to 100 or not, using this algorithm:

  1. Create a random number between 0 and 1
  2. Multiple that random number by the sum of your weightings
  3. Iterate through your options, keeping a running total of the weightings of all options considered so far. Once your running total is above the number you calculated, you have found your picked item

Some example code:

const options = [
    {
        id: 1, weight: 0.5
    },
    {
        id: 2, weight: 2
    },
    {
        id: 3, weight: 1
    },
];

const pick = function (options) {
    const weightTotal = options.reduce((sum, option) => sum   option.weight, 0);

    const seed = Math.random();
    const weightedSeed = seed * weightTotal;

    let runningTotal = 0;
    for (let option of options) {
        runningTotal  = option.weight;

        if (runningTotal > weightedSeed) {
            return option;
        }
    }
};

console.log(pick(options).id);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

This method requires you to have your available options be iterable, but their order doesn't matter since you're using a random seed anyway.

  • Related