-1

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);
}
thehennyy
  • 4,020
  • 1
  • 22
  • 31
  • 1
    Possible duplicate of [How do I remove duplicates from a C# array?](https://stackoverflow.com/questions/9673/how-do-i-remove-duplicates-from-a-c-sharp-array) – Jayendran Jul 31 '18 at 09:20
  • 3
    What is your actual problem? What does the code do and what did you expect instead? – MakePeaceGreatAgain Jul 31 '18 at 09:21
  • 2
    Be careful, you fill `index` with a random number, but in your `Console.WriteLine` you generate **another** random number. Is this what you intended to do? – Rafalon Jul 31 '18 at 09:21

2 Answers2

2

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

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • 1
    don't you think random shuffling the array is a more efficient appraoch with the same result? – fubo Jul 31 '18 at 09:27
  • 1
    @fubo do you mean `Names.OrderBy(x => r.Next()).ToArray();`? I think yes, but OP just ask about display the results without duplicatin, so I leave it as is – Roman Marusyk Jul 31 '18 at 09:32
0

Maybe this version adds some readability:

while (alreadyUsed.Count < Names.Length)
{
    var notUsedYet = Names.Except(alreadyUsed).ToArray();
    var index = r.Next(0, notUsedYet.Length);
    alreadyUsed.Add(notUsedYet[index]);
    Console.WriteLine("The 1st Winner is:  " + notUsedYet[index]);
}
Kristoffer Jälén
  • 4,112
  • 3
  • 30
  • 54