Search code examples
c#randomnames

In this situation how can i display the results without duplicatin ?:)


Describe it on a baby level im so beginner...

static void Main(string[] args)
{
    string[] Names = { "Erik", "Levente", "Noel", "Áron", "Krisztián", "Kristóf", "Bence", "Roland", "Máté", "László", "Bálint" ,
    "Regina", "Brigitta", "Gréta", "Hédi", "Hanna", "Boglárka", "Jázmin", "Réka", "Alexandra", "Rebeka", "Lili", "Luca", "Zsófi"};          

    List<string> alreadyUsed = new List<string>();
    Random r = new Random();
    while (alreadyUsed.Count < Names.Length)
    {
        int index = r.Next(0, Names.Length);
        if (!alreadyUsed.Contains(Names[index]))
            alreadyUsed.Add(Names[index]);
        Console.WriteLine("The 1st Winner is:  " + Names[r.Next(0, Names.Length - 1)]);
    }

    Console.ReadKey(true);
}

Solution

  • If you just want to display the results without duplicatin then try:

    while (alreadyUsed.Count < Names.Length)
    {
        int index = r.Next(0, Names.Length);
        if (!alreadyUsed.Contains(Names[index]))
        {
            alreadyUsed.Add(Names[index]);
            Console.WriteLine("The 1st Winner is:  " + Names[index]);
        }
    }
    

    Note that in Console.WriteLine I'm using the current added item Names[index] instead of Names[r.Next(0, Names.Length - 1)]