6

So here's the code I've been using. Its just a simple program to test to see if 3 randomly generated numbers are in ascending or descending order. For some reason if I'm using the debugger and stepping into every line then the code works properly. If not then it says the numbers are in order 100% or out of order 100%, which should not be the case.

Here is the code I've been using:

        int num1;
        int num2;
        int num3;

        int yes = 0;
        int no = 0;

        for (int i = 0; i <= 99; i++)
        {

            Random rnd = new Random();

            num1 = rnd.Next(1, 11);
            num2 = rnd.Next(1, 11);
            num3 = rnd.Next(1, 11);

            if ( ((num1 <= num2) && (num2 <= num3)) || ((num1 >= num2) && (num2 >= num3)) )
            {
                yes += 1;
            }

            else
            {
                no += 1;
            }

        }


        Console.WriteLine("The Number are in ascending order " + yes.ToString() + " Times");
        Console.WriteLine("The Number are not in ascending order " + no.ToString() + " Times");

        Console.ReadLine();

I think that it might be a problem with the pseudo random and the code generating the same 3 numbers every time, but I'm still learning more about programming and other help would be greatly appreciated.

vurhd1
  • 63
  • 3

2 Answers2

11

The new Random() constructor uses the current time as the seed.

Unless you wait in the debugger, all of your Random instances have the same seed.

You should use a single instance.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
7

This has to do with how the random numbers are generated.

If you take

Random rnd = new Random();

and move it out of the loop, you should see the desired results.

More background:

The random number generator uses a seed based on the time you instantiate it. Because your code is running so quickly, the seed is the same so the numbers are the same. This is why it works when you step through.

Instantiating the Random outside of the loop will instantiate it once and use the random algorithm to generate new numbers.

oppassum
  • 1,746
  • 13
  • 22