Home > Backend Development > C++ > Why Does My Random String Generator Produce Duplicate Outputs?

Why Does My Random String Generator Produce Duplicate Outputs?

Mary-Kate Olsen
Release: 2025-01-05 11:17:41
Original
233 people have browsed it

Why Does My Random String Generator Produce Duplicate Outputs?

Random String Generator Duplicating Output

Your goal is to generate two distinct four-character random strings. However, your current code returns duplicates.

Root Cause

The root cause lies in the initialization of the Random instance within the RandomString method. Each invocation of the method creates a new instance of Random, resulting in identical sequences of random numbers.

Solution

To ensure two unique random strings, move the initialization of the Random instance outside the method, into the class level. This ensures that a single instance is used throughout the lifetime of the class.

Modified Code

private static Random random = new Random((int)DateTime.Now.Ticks);

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);

// create full rand string
string docNum = Rand1 + "-" + Rand2;
Copy after login

Example Output

The modified code will generate two unique four-character random strings, such as:

UNTE-FWNU
Copy after login

instead of duplicates like:

UNTE-UNTE
Copy after login

By initializing the Random instance at the class level, you ensure that a consistent sequence of random numbers is used, resulting in unique random strings.

The above is the detailed content of Why Does My Random String Generator Produce Duplicate Outputs?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template