Choose one of several options with a certain probability.

I have a scenario where I need to show the user a different page for the same URL based on the probability distribution,

so, for example, for 3 pages the distribution may be

page 1 - 30% of all users
page 2 - 50% of all users
page 3 - 20% of all users

When you decide which page to load for a given user, which technique can I use to ensure that the overall distribution matches the above?

I think I need a way to select an object in "random" from the set X {x1, x2 .... xn}, except that instead of all objects being equally likely, the probability of choosing the object in advance is determined.


Thanks for putting everyone in, after creating the prototype, this is what I ended up using

private static int RandomIndexWithPercentage(Random random, int[] percentages) {
    if (random == null) {
        throw new ArgumentNullException("random");
    }

    if (percentages == null || percentages.Length == 0) {
        throw new ArgumentException("percentages cannot be null or empty", "percentages");
    }

    if(percentages.Sum() != 100) {
        throw new ArgumentException("percentages should sum upto 100");
    }

    if (percentages.Any(n => n < 0)) {
        throw new ArgumentException("percentages should be non-negative");
    }

    var randomNumber = random.Next(100);
    var sum = 0;
    for (int i = 0; i < percentages.Length; ++i) {
        sum += percentages[i];
        if (sum > randomNumber) {
            return i;
        }
    }

    //This should not be reached, because randomNumber < 100 and sum will hit 100 eventually
    throw new Exception("Unexpected");
} 
+3
1

0-9. 3, . 8, .


, :

private int ChoosePage()
{
    int[] weights = new int[] { 3, 5, 2 };
    int sum = 0;
    int i;
    for (i = 0; i < weights.Length; i++)
        sum += weights[i];
    int selection = (new Random()).Next(sum);
    int count = 0;
    for (i = 0; i < weights.Length - 1; i++)
    {
        count += weights[i];
        if (selection < count)
            return i;
    }
    return weights.Length - 1;
}

, - . sum= 100, weight[i] - i. , , - weight[i] weight[j], i , j. , , -. , , N, hardcode N in, . , .

+6

Source: https://habr.com/ru/post/1749672/


All Articles