mercredi 21 juillet 2021

How Exactly Works the Random Class in C#? [duplicate]

I want to understand why when I create a Random Number Generator in this example, instead of generating random number that eventually are the same (i.e. generate the number '3' two times), it always generate different ones without me coding anything. What I mean by that, is that when I Generate the password, it is always with the same size: 10 digits. What it means that when generating the "random" position of the password in wich we will insert the random digit, it magically never is the same, it never overwrites an already generate digit. Could you folks elucidate that for me? Thank in advance.

        private const string CapitalLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private const string SmallLetters = "abcdefghijklmnopqrstuvwxyz";
        private const string Digits = "0123456789";
        private static Random rng = new Random();
        private static StringBuilder password = new StringBuilder();

    static void Main(string[] args)
    {
        for (int i = 0; i < 2; i++)
        {
            char capitalLetter = GenerateChar(CapitalLetters);
            InsertAtRandomPosition(password, capitalLetter);
        }
        for (int i = 0; i < 6; i++)
        {
            char smallLetter = GenerateChar(SmallLetters);
            InsertAtRandomPosition(password, smallLetter);
        }
        for (int i = 0; i < 2; i++)
        {
            char number = GenerateChar(Digits);
            InsertAtRandomPosition(password, number);
        }

        Console.WriteLine(password);
    }

    private static char GenerateChar(string availableChars)
    {
        int randomIndex = rng.Next(availableChars.Length);
        return availableChars[randomIndex];
    }
    private static void InsertAtRandomPosition(StringBuilder password, char character)
    {
        int index = rng.Next(password.Length+1);
        password.Insert(index, character);
    }``



Aucun commentaire:

Enregistrer un commentaire