Luke
Luke

Reputation: 1

C# Randomising Questions in a Quiz for my school coursework

Hi so i have been having a bit of trouble with getting multiple questions to randomise whenever i try to pull questions from a text file.

 Random Num = new Random();
 int Qnumber = Num.Next(QandAClass1.Questions.Count);

 label8.Text = QandAClass1.Questions.Count.ToString();

 // counts items in the list and selects random number from it 
 label1.Text = QandAClass1.Questions[Qnumber];

 ///////////////////////////////////////////////////////
 Answer = QandAClass1.Answers[Qnumber];

 label2.Text = Answer; // Stores ans for selected question 
 ///////////////////////////////////////////////////////
 QandAClass1.Questions.RemoveAt(Qnumber);
 QandAClass1.Answers.RemoveAt(Qnumber);

 label8.Text = QandAClass1.Questions.Count.ToString();

This is the Code i have at the minute and this works great but only for one question. However i have five questions on the screen at once and i need them all to be random. they are just labels on a windows form. Any help or pointer would be greatly appreciated. Thanks :) PS label 8 on this form was just a checker for me to make sure all the right number of questions were being read in. Also my label 2 was just to check that the answer matched the question.

Upvotes: 0

Views: 231

Answers (1)

user1489673
user1489673

Reputation:

I suggest this approach. Get the basic process working. It is a method I often use for randomising items

  1. If possible, use a class that contains the question and answer (as already suggested)
  2. Create a list of these Questions and Answers
  3. Display a list of questions and answers

Once you are happy that this works, your last job is to randomise a list. Start with your main Question and Answer list but also, create a new, empty display list.

Randomly take a Question and Answer from your main list and add it to your display list. There is now one item in the display list and one less item in the main list. Repeat this approach until you have as many (random) display items or the main list is empty.

Each time you remove an item from the main list, the range for the index of the random number reduces by one.

Random rnd = new Random();
...
int randomIndex = rnd.Next(0, qaList.Count-1);

Upvotes: 1

Related Questions