I have the following code inside a static method in a static class:
Random r = new Random();
int randomNumber = r.Next(1,100);
I have this inside a loop and I keep getting the same randomNumber!
Any suggestions here?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You should not create a new
Randominstance in a loop. Try something like:The sequence of random numbers generated by a single
Randominstance is supposed to be uniformly distributed. By creating a newRandominstance for every random number in quick successions, you are likely to seed them with identical values and have them generate identical random numbers. Of course, in this case, the generated sequence will be far from uniform distribution.For the sake of completeness, if you really need to reseed a
Random, you’ll create a new instance ofRandomwith the new seed: