Use rand5(), to generate rand7() (with the same probability) [duplicate]

╄→尐↘猪︶ㄣ 提交于 2019-12-06 09:20:27

问题


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:


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);
}


来源:https://stackoverflow.com/questions/10464360/use-rand5-to-generate-rand7-with-the-same-probability

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!