dimanche 23 mai 2021

random empty list on 4th instance of List Shuffler [duplicate]

I'm using C# to write out a list shuffler for a list of possible answers for a multiple choice quiz game. THe list shuffler would shuffle the order of the items, and allow the answers to appear in a random order.

The code appears to function, but on the 3'rd or 4th instance of this code, it errors out with an indexoutofrange. While debugging, I've found that the unshuffledList is startingout empty.

The code is:

public static class ListShuffler
{public static List<string> ShuffleListItems(List<string> unshuffledList = null)
{
    List<string> shuffledList = new List<string> { };

    System.Random random = new System.Random();

    int index;
    if (unshuffledList == null )
    {
        shuffledList = new List<string>{ "error", "error", "error", "error" };
    }
    else {
        for (; unshuffledList.Count > 0;)
        {
            index = random.Next(0, unshuffledList.Count);
            shuffledList.Add(unshuffledList[index]);
            unshuffledList.RemoveAt(index);

            /* if (unshuffledList.Count == 1)
             {
                 shuffledList.Add(unshuffledList[0]);
                 unshuffledList.RemoveAt(index);
                 break;
             }
             */
        }
    } 
    
    
    
    return shuffledList;
}

}

The code is called using:

List<string> answerList = ListShuffler.ShuffleListItems(unshuffledList: question.Options);

The error is definitely somewhere in this block of code, since use of another list shuffler found online results in no error. I just want to understand where the error is coming from. Any help is appreciated!




Aucun commentaire:

Enregistrer un commentaire