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.
You are not generating random numbers in Rand5.
Do it like this: