mercredi 26 août 2020

Random number in Do While Loop C#

I have been trying to create a random string out of alphanumeric characters and to use Do-While Loop to check if the random string meet the requirement. Otherwise, it should continue the Do Loop. However, I found the code I have always generates the same string over and over again. To demonstrate, I set int message_length = 2 and ask While Loop to check if the generated string is "ab" like while (check != "ab").

I have tried to put Random seed = new Random() in the Do Loop, out of the Do Loop, and out of the Main() as you can see the code I commented out. None of them is working. I used Visual Studio 2017, Windows 10 Home. Anyone could help? Many thanks!

using System;
using System.Text;
using System.Collections.Generic;


public class Program
{
    //static Random seed = new Random();

    public static void Main(string[] arggs)
    {
        Random seed = new Random();
        const string src = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Console.WriteLine(src.Length);
        int string_length = 2;
        List<string> all_message = new List<string>();
        string check = "";
        do
        {
            //Random seed = new Random();
            int i = 0;
            StringBuilder message = new StringBuilder();
            for (int j = 0; j < string_length; j++)
            {
                char c = src[seed.Next(0, src.Length)];
                message.Append(c);
            }
            all_message.Add(message.ToString());
            check = all_message.ToString();
            Console.WriteLine(i + " = " + all_message[i]);

            i++;
        }
        while (check != "ab");

    }
}



Aucun commentaire:

Enregistrer un commentaire