2

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.

Community
  • 1
  • 1
Novak
  • 2,760
  • 9
  • 42
  • 63

1 Answers1

2

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);
}
adrianm
  • 14,468
  • 5
  • 55
  • 102
  • That worked, what is the difference between how I stated the rand5(), and yours? – Novak May 05 '12 at 17:51
  • 3
    Guy, the difference is that he keeps using the same rand object. There was actually a famous case where a lotto was won many times by someone who noticed a similar glitch in computer programming. The issue is that to make random numbers the computer needs to establish a "seed". You recreating it every time you do "new" actually stops it from being random since it patternizes the creation of this seed value the computer utilizes. – Dylan - INNO Software May 05 '12 at 17:58
  • 1
    Random uses a fixed sequence of random numbers. When you do `new Random` you select a starting position within the sequence based on the current time. Since you call `new Random` all the time you select the same starting position every time and get the same number back. My code select the starting point once and then return the next number from the sequence every time. – adrianm May 05 '12 at 17:58
  • Thanks andrianm and Dylan, now I do understand. By the way, do you know what seed the c# Random class is based on? just the current time? – Novak May 05 '12 at 17:59
  • 1
    The documentation just says "The default seed value is derived from the system clock and has finite resolution" http://msdn.microsoft.com/en-us/library/h343ddh9.aspx – adrianm May 05 '12 at 18:03