+ 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

26th Jan 2019, 7:18 AM
Rowsej
Rowsej - avatar
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}"); }
26th Jan 2019, 7:25 AM
Hatsy Rei
Hatsy Rei - avatar
+ 6
Thank you Hatsy Rei!
27th Jan 2019, 1:35 AM
Rowsej
Rowsej - avatar