in reply to Re^2: Averages in bowling
in thread Averages in bowling
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?)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Averages in bowling
by Andrew_Levenson (Hermit) on Mar 21, 2006 at 22:03 UTC | |
by ikegami (Patriarch) on Mar 21, 2006 at 22:20 UTC | |
by Andrew_Levenson (Hermit) on Mar 21, 2006 at 23:36 UTC |