how do I get random question from pool of questions

38 Views Asked by At

I have 50 random questions, 1, 2,3... 50.. I want to show 5 questions to user, Let say user start, random 5 questions I need to show to user one by one.

Question should not repeat...

I am using .net core web api...

{
Math.Random...
}

In my question sometime it get duplicate question....means same question user getting again..


how can I manage this?
1

There are 1 best solutions below

2
On

This can be achieved with a list.

Inside a loop that repeats 5 times:

  • Take a random index from 0 to length of list
  • Save the item in that position
  • Remove it from the list

This way, it won't be in the list for the next loops.

Example code:

List<string> questions = ...; // Your question pool
Random rnd = new Random();

string[] selectedQuestions = {"", "", "", "", ""}; // Your 5 selected questions
for (int i = 0; i < 5; i++) {
  int indx = rnd.Next(0, questions.Count);

  selectedQuestions[i] = questions[indx];
  questions.RemoveAt(indx);
}