Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi All, I'm writing a program (Gui - TK) of multiple choice quiz. i got a file (txt) called Questions which contain 10 question and an additional file called Answers which contains 10 answers. i want each question to have 4 answers one of the four will one correct. i tried working with "Data::Random::WordList" for the random que + ans,but in some cases non of the answers are correct. so...i need advice on how to: A. pick 1 random question from the Questions text file B. ALWAYS pick the right answer and 3 random wrong answers from the Answers text file Thanks.

Replies are listed 'Best First'.
Re: Perl ( multiple Choice Tests )
by kennethk (Abbot) on Jul 28, 2010 at 17:26 UTC
    What have you tried? What didn't work? Presumably you have some code, since the problem you describe wouldn't appear until you had some. I see no reason why you didn't post it to help us help you. See How do I post a question effectively?.

    Assuming you have some way of identifying the correct answer implies you have access to that data. Therefore you could use List::Util::shuffle once you have all elements in a single list. Something like:

    use List::Util qw(shuffle); use Data::Random::WordList; my $correct = "Correct answer"; my $wl = new Data::Random::WordList( wordlist => '/usr/dict/words' ); my @rand_words = $wl->get_words(3); my @answers = shuffle(@rand_words, $correct);
Re: Perl ( multiple Choice Tests )
by talexb (Chancellor) on Jul 28, 2010 at 17:33 UTC
      A. pick 1 random question from the Questions text file

    Read the questions from the question file into an array, and randomly pick one of the array elements using rand.

      B. ALWAYS pick the right answer and 3 random wrong answers from the Answers text file

    Using the question number from the last step, go get the correct answer from the answer file, possibly again reading the answers file into an array.

    For the wrong answers, make some stuff up and put it in a bad answers file. Read that file into an array as before, and randomly select three distinct answers (distinct, because you don't want the same wrong answer twice). Order these three answers and the correct answer randomly and display. Done!

    Alex / talexb / Toronto

    "Groklaw is the open-source mentality applied to legal research" ~ Linus Torvalds