vendredi 11 mai 2018

C# - Generating random username with up to 3 digits puts 4 digits sometimes

I have to write method to generate random username which contains 8 characters, consisting of lowercase letters and up to 3 digits. So I wrote following method:

    public string UsernameGenerator()
    {
        const string letters = "abcdefghijklmnopqrstuvwxyz";
        const string digits = "0123456789";
        var builder = new StringBuilder();
        Random random = new Random((int)DateTime.Now.Ticks);
        int numberOfNumerics = random.Next(0, 4);

        for (int i = 0; i < 8; i++)
        {        
            var l = letters[random.Next(0, letters.Length)];
            builder.Append(l);
        }

        for (int i = 0; i < numberOfNumerics; i++)
        {
            int replaceIndex = random.Next(0, 8);
            var d = digits[random.Next(0, digits.Length)];
            builder.Replace(builder[replaceIndex],d);
        }

        return builder.ToString();
    }

However from time to time it generates username that contains 4 digits. My numberOfNumerics variable is random.Next(0,4), according to documentation it should return random number from 0 to 3. It looks like additional number is duplicate of one of already used digits and it's often placed next to each other. Some examples of wrongly generated password:

ko90w09q, qs2b22m6, yh38wa88, x66uvf36

And yes, changing random.Next(0, 4); to random.Next(0, 3); kinda solves the problem, because then it generates username with 3 digits from time to time, but it's indirectly solution for me. Any help appreciated!




Aucun commentaire:

Enregistrer un commentaire