2010/07/27

No cure for geekiness

Alyssa is learning the multiplication chart recently and likes to ask me to test her all the time. Being a lazy geek, here is my solution in perl:


#!/usr/bin/perl -w
my $script_name = 'multiplication_test.pl';

# Chih-Horng Kuo
# multiplication skill test

use strict;
use warnings;

my $answer = 0;
my $count_question = 0;
my $count_correct = 0;
my $count_wrong = 0;

print "\n";
print "*** Multiplication Test\n";
print "*** Type 'quit' to end the test.\n\n";

while (1) {
$count_question++;
# get 2 random integers
# the first one should be between 2 and 9
my $a = int(rand(8)) + 2;
# the second one should be between 1 and 9
my $b = int(rand(9)) + 1;

print "\n";
print "\tQ$count_question:\t$a x $b = ";
$answer = <>;
chomp $answer;

if ( $answer =~ /(\d+)/ ) {
if ( $answer == ( $a * $b ) ) {
$count_correct++;
print "\t\t\tYeah!\n";
}
else {
$count_wrong++;
print "\t\t\tOops. The correct answer is ", $a * $b, ".\n";
}
}
elsif ($answer eq 'quit' ) {
last;
}
else {
print "\t\tYour answer is not a number. Try again!\n";
}
}
print "\n";
print "*** Thank you for playing!\n";

my $count_total = $count_correct + $count_wrong;

if ( $count_total > 0 ) {
my $score = int ( ( $count_correct / $count_total ) * 100 );
print "*** Your got $count_correct questions right",
" and $count_wrong questions wrong.\n";
print "*** Your score is $score%\n";
if ( $score >= 90 ) {
print "*** Great job!\n";
}
elsif ( $score >= 75 ) {
print "*** Good work.\n";
}
elsif ( $score >= 60 ) {
print "*** That's okay.\n";
}
else {
print "*** Try harder next time.\n";
}
}


Initially I wasn't sure if it's a good idea to use a while loop, however, after she got a chance to play with it, I am very glad about the decision. She simply can't stop!
Post a Comment