0

Hello fellow programmers! I would like some help on my code please. The following program randomizes my class' seating order. However, some elements from my list appear to be repeating. Is there any way to alter this piece of code in order to receive different seating orders without repeating any of the elements in my list? I thank you all in advance!!

List<string> list = new List<string>();

list.AddRange(new String[]
{                
    "Daria", "Denisa", "Erica",
    "Merlin", "Nicoletta", "Mia",
    "Lilian", "Karel", "Luveesh",
    "Milan", "Oliver","Tea",
    "Carlos", "Raneem", "Marsha",
    "Uros", "Oguzhan"
});

Random random = new Random();
Console.WriteLine("Type 'x' then hit 'Enter':");

string userInput = Console.ReadLine();

if (userInput == "x")
{
    foreach (var item in list)
    {
        Console.WriteLine("");
        Console.WriteLine("Table 1: " + "" + list[random.Next(0, list.Count)] + "," + "" + list[random.Next(1, list.Count)]);
        Console.WriteLine("Table 2: " + "" + list[random.Next(2, list.Count)] + "," + "" + list[random.Next(3, list.Count)]);
        Console.WriteLine("Table 3: " + "" + list[random.Next(4, list.Count)] + "," + "" + list[random.Next(5, list.Count)]);
        Console.WriteLine("Table 4: " + "" + list[random.Next(6, list.Count)] + "," + "" + list[random.Next(7, list.Count)]);
        Console.WriteLine("Table 5: " + "" + list[random.Next(8, list.Count)] + "," + "" + list[random.Next(9, list.Count)]);
        Console.WriteLine("Table 6: " + "" + list[random.Next(10, list.Count)] + "," + "" + list[random.Next(11, list.Count)]);
        Console.WriteLine("Table 7: " + "" + list[random.Next(12, list.Count)] + "," + "" + list[random.Next(13, list.Count)]);
        Console.WriteLine("Table 8: " + "" + list[random.Next(14, list.Count)] + "," + "" + list[random.Next(15, list.Count)]);
        Console.WriteLine("Table 9: " + "" + list[random.Next(16, list.Count)]);
        Console.ReadLine();
    }
}
maccettura
  • 10,514
  • 3
  • 28
  • 35
  • 1
    Could you remove them from the list as you use them? then instead of starting higher each time, leave your random call as `random.Next(0,list.Count)` – Michael Sharp Nov 14 '17 at 19:51
  • 6
    Your best bet is almost certainly to shuffle the list with a Fisher Yates shuffle. See https://stackoverflow.com/questions/273313/randomize-a-listt – Chris Nov 14 '17 at 19:51
  • 3
    There is a whole lot wrong with this. Why are you looping through the list at all? Why are you using a list if you already have an array? – maccettura Nov 14 '17 at 19:52

0 Answers0