Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code runs correctly only when stepping through it with debugger? [duplicate]

Possible Duplicate:
Random number generator only generating one random number

I was a bit baffled with this few moments ago. I have the following code:

public blockType generateRandomBlock()
{
    Random random = new Random();
    int makeBlockOfType = random.Next(0, 100);

    blockType t = blockType.normal;
    if (makeBlockOfType <= 80 && makeBlockOfType >= 60)
    {
        t = blockType.blue;
    }
    else if (makeBlockOfType > 80 && makeBlockOfType <= 95)
    {
        t = blockType.orange;
    }
    else if (makeBlockOfType > 95 && makeBlockOfType <= 100)
    {
        t = blockType.green;
    }

    return t;
}

Fairly simple, it return an enum value based on a randomly generated number (based of system time). Unfortunately for some odd reason, I have all blocks either one color or the other even though this runs for every single block being put into the game. However, when I step through this with the debugger and then see the results after some run, I see that the blocks are now multi colored based on the chances provided. I am a little bit confused about why this is happening.

For this I am using MonoGame which uses the Mono compiler instead of the Microsoft one. Could this be the issue? I have tried to put this code inline into the constructor from where it is being called but I am getting the same result (I am guessing the compiler inlines the code anyways).

I have tried to restart Visual Studio it separately rather than letting the run do the build; no changes.

Any suggestions and help are greatly appreciated!

like image 516
Serguei Fedorov Avatar asked Dec 12 '12 14:12

Serguei Fedorov


1 Answers

You should instanciate Random only once (set it as a private field and instanciate in the constructor), see the similar question : Random.Next returns always the same values

See the Random documentation :

The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated

In your case, you create a Random instance with the same seed (too close in time) and you take the first value which will be the same for a given seed.

like image 148
AlexH Avatar answered Sep 22 '22 15:09

AlexH