Generate Random Weighted value

前端 未结 6 1458
隐瞒了意图╮
隐瞒了意图╮ 2020-12-28 10:19

Edit: I\'ve rewritten the question in hopes that the goal is a little clearer.

This is an extended question to this question here, and I really like

6条回答
  •  别那么骄傲
    2020-12-28 10:50

    Assuming you can cope with whole numbers for the percentages, just assign each value between 0 and 99 a result - e.g. 0-9 could have a result of 1 and 95-99 could have a result of 6 (to give your 10%=1 and 5%=6 scenario). Once you've got that translation function (however you achieve that - there are various approaches you could use) you just need to generate a random number in the range 0-99 and translate it to the result.

    Your question isn't really clear in terms of the code you want (or even which language - C# or PHP?) but hopefully that will help.

    Here's some C# code which will let you get any bias you like, within reason - you don't have to express it as percentages, but you can do:

    static int BiasedRandom(Random rng, params int[] chances)
    {
        int sum = chances.Sum();
        int roll = rng.Next(sum);
        for (int i = 0; i < chances.Length - 1; i++)
        {
            if (roll < chances[i])
            {
                return i;
            }
            roll -= chances[i];
        }
        return chances.Length - 1;
    }
    

    So for example, you could use

    int roll = BiasedRandom(rng, 10, 10, 10, 10, 10, 50) + 1;
    

    which will give a 10% chance for each of 1-5, and a 50% chance of getting a 6.

提交回复
热议问题