Need help with a list

ykostov

New member
Joined
Jan 2, 2022
Messages
1
Programming Experience
Beginner
Hello Devs, (beginner here :) )
I have a code in Windows Forms 2022 C# .Net framework

I have a list
C#:
 public List<int> qList = new List<int>(26);
and a qnum check
C#:
Random r = new Random();
            int qnum = r.Next(1, 25);


            if (qList.Contains(qnum)) { wasChosen = true; }
            else
            {
                if (wasChosen == false)
The goal here is to have random chosen "questions", not duplicated. Idk is that the way it should be done. Github repo: https://github.com/ykostov/driving-flyers/tree/main/driving5 .

Best Regards,
ykostov
 
Last edited by a moderator:
As a quick aside in C# lists are zero based. With you selecting a random number between 1-24 (inclusive), you'll never have a chance of picking the first item or last item's which would be at index 0 and 25 respectively.

If you want truly random, then you should allow for duplicate questions. If like flipping a coin. Are you saying that if you flip a coin and get heads on the first toss, then the next toss should be tails?

It sounds like what you really want is to shuffle the questions in your list. The best way accomplish this is to actually shuffle the list using the Fisher-Yates shuffle.

To get an equivalent effect, what you can do is randomly pick an index into the list, and then remove that item from the list so that next random call will never pick that question again. In pseudo code:
C#:
initialize list with questions
while (list.Count > 0 AND not quit)
{
    int qnum = random.Next(0, list.Count);
    show list[qnum]
    list.RemoveAt(qnum);
}
 
Also thanks for attempting to put your code in Markdown code tags. Unfortunately this forum doesn't currently support Markdown, it only does BBCode.
 
It's quite easy to shuffle a list using the Random class, as long as you're OK with creating a new list, e.g.
C#:
private void Shuffle<T>(ref List<T> list)
{
    var rng = new Random();

    list = list.OrderBy(t => rng.NextDouble()).ToList();
}
If there's any chance that that method will be called multiple times in quick succession then you should create a single Random object outside the method, rather than a new one each time inside.

You can then do this:
C#:
var qList = new List<int>();

// Populate list here.

Shuffle(ref qList);

foreach(var q in qList)
{
    // Use q here.
}
Alternatively, if you want to use one item at a time, populate a Queue<int> or Stack<int> with the shuffled data and then Dequeue or Pop an item as required.
 
Back
Top Bottom