Jamie Keeling
Jamie Keeling

Reputation: 9966

Generating random questions from a text file - C#

I want to provide the user with a selection of questions but I want them to be random, having a quiz game with the same questions isn't exactly fun.

My idea was to store a large collection of questions and there appropiate answers in a text file:

What colour is an Strawberry|Red
How many corners are there on a Triangle|Three

This means that I could simply select a line at random, read the question and answer from the line and store them in a collection to be used in the game.

I've come up with some pseudo code with an approach I think would be useful and am looking for some input as to how it could be improved:

Random rand = new Random();
int line;
string question,answer;

for(int i = 0; i < 20; i++)
{
   line = rand.Next();
   //Read question at given line number to string
   //Read answer at given line number to string
   //Copy question and answer to collection
}

In terms of implementing the idea I'm unsure as to how I can specify a line number to read from as well as how to split the entire line and read both parts separately. Unless there's a better way my thoughts are manually entering a line number in the text file followed by a "|" so each line looks like this:

1|What colour is an Strawberry|Red
2|How many corners are there on a Triangle|Three

Thanks for any help!

Upvotes: 2

Views: 3594

Answers (2)

Rob Fonseca-Ensor
Rob Fonseca-Ensor

Reputation: 15621

You don't want to display any questions twice, right?

Random random = new Random();
var q = File.ReadAllLines("questions.txt")
    .OrderBy(x=>random.Next())
    .Take(20)
    .Select(x=>x.Split('|'))
    .Select(x=>new QuestionAndAnswer(){Question=x[0],Answer=x[1]});

Upvotes: 2

Reese Moore
Reese Moore

Reputation: 11640

Why not read the entire file into an array or a list using ReadLine and then refer to a random index within the bounds of the array to pull the question/answer string from, rather than reading from the text file when you want a question.

As for parsing it, just use Split to split it at the | delineator (and make sure that no questions have a | in the question for some reason). This would also let you store some wrong answers with the question (just say that the first one is always right, then when you output it you can randomize the order).

Upvotes: 2

Related Questions