Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Summing Up Array Elements By Group

by fullermd (Priest)
on Jan 21, 2009 at 08:51 UTC ( [id://737778]=note: print w/replies, xml ) Need Help??


in reply to Summing Up Array Elements By Group

For another alternate approach, first roll up the groups of 3 into array refs, then sum them up:

# Initial values my @arr = (1,2,3, 4,5,6, 7,8,9); # Replace with a set of array refs to 3-element arrays my $nblk = @arr / 3; my @a2; push @a2, [@arr[$_*3, $_*3+1, $_*3+2]] for (0..$nblk-1); # Sum up each array ref use List::Util qw(sum); my @a3 = map { sum @$_ } @a2;

Thus we end up with:

@a3 = ('6', '15', '24');

By itself, it's a pretty roundabout version of what ivancho did above. But if you can use the grouping in other places in the program, it can be useful to group them up like that early on.

Of course, if you don't, you skip the extra step and it collapses down to

use List::Util qw(sum); push @a3, sum @arr[$_*3, $_*3+1, $_*3+2] for (0..$nblk-1);

which is just another way of writing ivancho's second version.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://737778]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (4)
As of 2024-04-25 16:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found