Use rand5(), to generate rand7() (with the same pr

2019-04-13 17:52发布

Possible Duplicate:
Expand a random range from 1–5 to 1–7

I have seen the question in here: Link

The solution the author provided didn't seem to generate the same probability.

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

Maybe I understood wrong, or I wrote the algorithm wrong, 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.

1条回答
我想做一个坏孩纸
2楼-- · 2019-04-13 18:08

You are not generating random numbers in Rand5.

Do it like this:

static Random rand = new Random()
static int rand5()
{
    return rand.Next(1, 6);
}
查看更多
登录 后发表回答