Home >Backend Development >C++ >Why Does My Random String Generator Return Identical Strings?
Your goal is to generate two distinct random strings, each with four characters. However, your current code produces two identical strings.
The issue stems from the creation of a new Random instance within the RandomString method. Since this instance is initialized for each call, it generates the same sequence of random numbers, resulting in duplicate strings.
To ensure two unique strings, we need to ensure the Random instance is created only once. We can do this by making the instance static and initializing it using a seeded value, such as the current time in ticks:
private static Random random = new Random((int)DateTime.Now.Ticks);
By making the instance static and using a seed, we ensure that the random number sequence is different for each call to the RandomString method, as demonstrated in the modified code below:
private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden private string RandomString(int size) { StringBuilder builder = new StringBuilder(); char ch; for (int i = 0; i < size; i++) { ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); builder.Append(ch); } return builder.ToString(); } // get 1st random string string Rand1 = RandomString(4); // get 2nd random string string Rand2 = RandomString(4); // creat full rand string string docNum = Rand1 + "-" + Rand2;
With this modification, your code will now generate two distinct random strings each time it is executed.
The above is the detailed content of Why Does My Random String Generator Return Identical Strings?. For more information, please follow other related articles on the PHP Chinese website!