Zagano
Zagano

Reputation: 139

Algorithm that randomly brings the bigger numbers more from an array

I did research and found the algorithm for small lists in general. I have some arrays such:

arr = [1,2,3,4 .... , 96,97,98,99,100];

arr2 = [105, 110, 165, 170];

arr3 = [1,2,7,8,9];

I want to send these arrays to a function and get random numbers from this array, but I want to have a higher probability of getting bigger numbers every time.

For example in array 1, the probability of 96 should be more than 4, but the probability of 97 should be more than 96.

How to generate a random weighted distribution of elements

Usually the solutions are like in this topic. However, this can cause performance problems with my arrays.

How can I achieve that?

Upvotes: 1

Views: 153

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386620

You could calculate the probabilities and pick the value.

For using it with a custom array take random

getRandomValue = random(sortedArray),

and later in a loop

let value = getRandomValue();

const
    random = sortedValues => {
        let length = sortedValues.length,
            sum = length * (length + 1) / 2;

        return () => {
            let r = Math.random();
            return sortedValues.find((_, i) => (r -= (i + 1) / sum) <= 0);
        };
    },
    getRandomValue = random([6, 7, 8, 9, 10]),
    counts = {};

for (let i = 0; i < 1e6; i++) {
    let value = getRandomValue();
    counts[value] = (counts[value] || 0) + 1;
}

console.log(counts);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Related Questions