Use rand5 () to generate rand7 () (with the same probability)

Possible duplicate:
Expand a random range from 1-5 to 1-7

I saw a question here: Link

The solution provided by the author does not seem to give the same probability.

For example, the number 4 of 10k calls for a function was returned 1-2 times (when other numbers, for example 2, were returned about 2k times).

Perhaps I misunderstood, or I wrote the algorithm incorrectly, but here:

    static int rand5()
    {
        return new Random().Next(1, 6);
    }
    static int rand7()
    {
        while (true)
        {
            int num = 5 * (rand5() - 1) + rand5();
            if (num < 22) return ((num % 7) + 1);
        }
    }
    static void Main(string[] args)
    {
        int limit = 10000;
        int[] scores = new int[7];
        for (int i = 0; i < limit; i++)
        {
            scores[rand7() - 1]++;
        }
        foreach (int n in scores)
        {
            Console.Write(n + " ");
        }
        Console.WriteLine();
    }

Thanks in advance.

+2
source share
1 answer

You do not generate random numbers in Rand5.

Do it like this:

static Random rand = new Random()
static int rand5()
{
    return rand.Next(1, 6);
}
+2
source

All Articles