How can I get a single random number from multiple possible ranges?

Viewed 491

I would like to be able to generate a (pseudo)random number from n possible ranges, where a range is x, y and x < y. For example, executing this code:

for(int i = 0; i < 10; i++)
{
    Console.Write(Random.NextRanges(new Range(1, 6), new Range(10, 16), new Range(20, 31)) + " ");
}

will produce something like:

3 12 5 22 1 27 29 5 10 24

The signature of the method NextRanges is:

public static int NextRanges(params Range[] ranges)

And Range is defined as:

public struct Range
{
    public int X;
    public int Y;

    public Range(int x, int y)
    {
        if (x >= y) throw new ArgumentException("x must be less than y.");
        X = x;
        Y = y;
    }
}

The only thing I'm not sure on is how to implement NextRanges, what the most efficient way or the most random way is (I know random can be tricky sometimes). Would you choose a random Range and then use Random.Next() on that? Or would you keep choosing random numbers until you got one that was within each of the ranges?

Is it also possible to weight the ranges so that a range of 0-100 has far more weight than a range of 100-102, for example?

1 Answers
Related