Search code examples
c#mathrandom

How To Make Selection Random Based On Percentage


I have a bunch of items than range in size from 1-10.

I would like to make the size that the item is to be determined by the percentage or chance of the object being that size..

For example:

Items chance of being size 1 = 50% chance

Items chance of being size 5 = 20% chance

Items chance of being size 10 = 5% chance

I know I would need to use a Random generator for this of course.

But just wondering how would some of you go about the logic of this in C#?


Solution

  • First of all: the probabilities provided don't add up to 100%:

    50% + 20% + 5% = 75%
    

    So you have to check these values. You may want to generate these per cents:

    // Simplest, but not thread safe
    private static Random s_Random = new Random();
    
    ...
    int perCent = s_Random.Next(0, 100);
    
    if (perCent < 50)               //  0 .. 49
    {
        // return Item of size 1
    }
    else if (perCent < 50 + 20)     // 50 .. 69
    {
        // return Item of size 5
    }
    else if (perCent < 50 + 20 + 5) // 70 .. 74 
    {
        // return Item of size 10
    } 
    ...