5

Possible Duplicate:
random string generation - two generated one after another give same results

I am writing a simple dice game for windows phone 7, that involves rolling two dice at the same time. Here is my Dice Roll Code:

 private int DiceRoll()
    {
        int result;
        Random rnd = new Random();

        result = rnd.Next(1, 7);
        return result;
    }

I then have this code that rolls the dice when a button is clicked:

   private void roll_Click(object sender, RoutedEventArgs e)
    {
        roll1 = DiceRoll();
        roll2 = DiceRoll();}

My problem is that both die get the same result.

Any idea how I can get a rolling algorithm that will usually return different results, but occasionally return the same?

Community
  • 1
  • 1
BigPete
  • 779
  • 2
  • 9
  • 21

3 Answers3

12

The default seed for Random is based on the current time. To quote the documentation,

As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers.

That is exactly what you should do: create one instance of Random and use it to generate all your random numbers.

Anomie
  • 92,546
  • 13
  • 126
  • 145
4

You need to keep one Random object around and reuse it; every time you create a new Random object, you effectively reset the sequence of numbers to begin in the same place. Store the Random object as a member variable someplace. You'll also want to seed it with a different value each time you run the program -- for example, a value based on the system clock time.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • 1
    Doesn't the random function in C# automatically seed from the system time though? – BigPete Mar 19 '11 at 02:11
  • Correct, except that you don't have to seed it, it's already seeded with a time dependent value (http://msdn.microsoft.com/en-us/library/h343ddh9.aspx) – steinar Mar 19 '11 at 02:12
  • 1
    @BigPete: You are correct, the default seed is based on the system time. – Anomie Mar 19 '11 at 02:13
  • 2
    @BigPete: correct, but if you create two Random objects in quick succession they are likely to have the same seed because of the finite resolution of the system time. – Gary Kerr Mar 19 '11 at 02:16
4

The clear majority of 'random number' tools I've seen fail badly if you allocate two or more random objects in a single application. You're allocating a new Random object for every invocation, and each time they are going to be seeded with something pretty weak, and maybe even identical seeds.

So, generate a single Random object and use it over the life of your application.

sarnold
  • 102,305
  • 22
  • 181
  • 238