[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Efficiency of String operators vs. arrays



aminzade@sover.net (Russell Aminzade)
>I'm working on a general-purpose multiple-choice quiz engine for the
>Internet.  This would include multiple answers with more than one correct
>answer (e.g. checkboxes rather than radio buttons on an HTML form).  It's a
>lot of fun (and work), but as I work on it I was wondering which would be
>more efficient...storing the user's answers and the correct answers in
>arrays, or strings.
[...]
>@user_answ=("A","D","E");
>@corr_ans=("B","D");
[...]
>or, I could put them into strings like this
>
>$user_answ=("ADE");
>$corr_ans=("BD");

The most elegant might be to use an associative array:

%corr_ans = ("A" => 1, "D" => 1, "E" => 1);
%correct  = ();
%bzzt     = ();
%missed   = %corr_ans;

foreach $answer (@user_answ) {
    if ($corr_ans{$answer}) {
        undef $missed{$answer};
        $correct{$answer} = 1;
    } else {
        $bzzt{$answer} = 1;
    }
}

After that, the results will be 

keys %correct;
keys %missed;
keys %bzzt;

Might not be the fastest, but it eliminates duplicates and is reasonably
straightforward.

Matthias

-----
Matthias Neeracher   <neeri@iis.ee.ethz.ch>   http://www.iis.ee.ethz.ch/~neeri
   "One fine day in my odd past..." -- Pixies, _Planet of Sound_