Jeff Borders wrote:
Hello, (revised to include entire program, input file, and output)
Okay, that's better. :)
I've written a simple quiz program and I've run into a problem with rand
and the integer it returns. It seems that it will eventually choose
either 0 or n+1 (I'm guessing) which blows up my array. I want to make
sure it chooses from the entire pool of questions. ie. Don't skip the
first and last array item. What suggestions can anyone give me?
Your problem seems to have little to do with the rand() function, and
much to do with how you create and use the arrays.
while (<DICT>) {
chomp;
$number_of_questions++;
($answer, $question) = split /\s*=\s*/;
$answer[$number_of_questions] = $answer;
$question[$number_of_questions] = $question;
}
close DICT;
Your sample data include 8 questions, but here you make both @answer and
@question contain 9 elements, of which the first is undef. That's
because the index of the first element in an array is 0, not 1.
do {
$total++;
$random_question = int(rand($number_of_questions));
Since $number_of_questions is 8, $random_question may be something
between 0 and 7, while you need 1 - 8 considering how you designed the
arrays.
$random_question = 1 + int(rand($number_of_questions));
print "$i. $answer[int(rand($number_of_questions))]\n";
#print incorrect value from array.
print "$i. $answer[1 + int(rand($number_of_questions))]\n";
Optionally you can prevent the undefined first element when creating the
arrays.
A style thing you should reconsider is the declaration of variables.
Lexical variables should preferrably be declared in the smallest
possible scope when you first use them. So variables that are only used
in the do {} block should be declared within the do {} block instead of
in the beginning of the program, etc.
--
Gunnar Hjalmarsson
Email: http://www.gunnar.cc/cgi-bin/contact.pl
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>