So the average is by bowler? Then you only need two counter variables, not three. If you'd give your vars more meaningful names, it would go much easier. I'm going to try to do this intructively.
  1. What is it you want to do? You want to calculate the average score of every bowler.

  2. That means you need to loop for every bowler:

    for my $bowler (0..3) { ... }

    Better yet, let's not assume we know how many games there are:

    for my $bowler (0..$#scores) { ... }

    We will be working with the scores of a specific bowler, so let's create a shortcut:

    for my $bowler (0..$#scores) { my $bscores = $scores[$bowler]; ... }
  3. Now, we need to calculate the average score of a bowler:

    $averages[$bowler] = int(($bscores->[0] + $bscores->[1] + $bscores->[2])/3);

    That's ok, but it could be better. We could use a loop to remove the redundancy and to avoid assuming we know how many games there are:

    my $sum = 0; for my $game (0..$#$bscores}) { $sum += $bscores->[$game]; } $averages[$bowler] = int($sum/@$bscores);

    We can clean it up a bit by using a foreach loop (since $game is only used as an index into @$bscores):

    my $sum = 0; $sum += $_ foreach @$bscores; $averages[$bowler] = int($sum/@$bscores);
  4. All together now:

    for my $bowler (0..$#scores) { my $bscores = $scores[$bowler]; my $sum = 0; $sum += $_ foreach @$bscores; $averages[$bowler] = int($sum/@$bscores); }
  5. You could even use List::Util to do the sum:

    use List::Util qw( sum ); for my $bowler (0..$#scores) { my $bscores = $scores[$bowler]; $averages[$bowler] = int(sum(@$bscores)/@$bscores); }

    (Why isn't that module part of core?)


In reply to Re^3: Averages in bowling by ikegami
in thread Averages in bowling by Andrew_Levenson

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.