Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RandomNumber method returns same number every time called

Tags:

c#

random

I am trying to generate a different random number every time my RandomNumber method is called from within my for loop. Right now, it returns the same number every time.

This is my RandomNumber method:

    private int RandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }

This is the context I am using it in: (it's a little messy just because I have been messing with trying to get it to work....)

        for (int i = 0; i < charsRaw.Length; i++)
        {
            int max = charsRaw.Length - 1;
            int rand = 0;
            rand = RandomNumber(0, max);

            charsNew[i] = charsRaw[rand];
            text2 += charsNew[i];

         }

I can't seem to get it to return a different value every time it is called with the for loop.

Although, when i stick a MessageBox.Show(rand.ToString()) after text2 += charsNew[i], it gives me a different value every time and works the way I intended it to. Strange.

Thanks! Eric

like image 219
Eric Avatar asked Jun 17 '09 03:06

Eric


People also ask

Why is Rand returning the same number?

The RAND function in stand-alone applications generates the same numbers each time you run your application because the uniform random number generator that RAND uses is initialized to same state when the application is loaded.

Can you generate the same random numbers everytime?

random seed() example to generate the same random number every time. If you want to generate the same number every time, you need to pass the same seed value before calling any other random module function.

What happens if you use the random number multiple times in your program?

If you use randomNumber() multiple times in your program it will generate new random numbers every time. You can think of each randomNumber() like a new roll of a die.


2 Answers

Instantiate Random once. Call .Next() multiple times on the same instance.

MSDN:

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

If you do wish to repeatedly instantiate Random, use a different seed each time.

like image 105
anthony Avatar answered Oct 21 '22 05:10

anthony


There's nothing saying a truly random sequence can't be the same number each time! :-) There is a small probability it's legit so you can never truly be sure. ducks for cover

like image 42
veroxii Avatar answered Oct 21 '22 04:10

veroxii