What is it you want to do? You want to calculate the average score of every bowler.
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]; ... }
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);
All together now:
for my $bowler (0..$#scores) { my $bscores = $scores[$bowler]; my $sum = 0; $sum += $_ foreach @$bscores; $averages[$bowler] = int($sum/@$bscores); }
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |