+ 8
[SOLVED] C# duplicate random numbers
While testing in a C# code, I found that the same numbers were being generated by my random() method. Is there any way around this? Here is a code which shows it happening: https://code.sololearn.com/cgK81DST69JK/?ref=app
2 Answers
+ 12
Declare and initialize the Random object outside the scope of the method, and use the same object for generating random numbers instead of dynamically creating a new one every time the function is called.
static Random rand = new Random();
static void random() {
int a = rand.Next(0, 6);
int b = rand.Next(0, 6);
Console.WriteLine(quot;{a} | {b}");
}
+ 6
Thank you Hatsy Rei!