tags:

views:

611

answers:

6

Hi. I have two arrays:

@arr1 = ( 1, 0, 0, 0, 1 );
@arr2 = ( 1, 1, 0, 1, 1 );

I want to sum items of both arrays to get new one like

( 2, 1, 0, 1, 2 );

Can I do it without looping through arrays?

+5  A: 

If you're using Perl 6:

@a = (1 0 0 0 1) <<+>> (1 1 0 1 1)  #NB: the arrays need to be the same size

The Perl 6 Advent Calendar has more examples.

rjstelling
But what about Perl 5?
Dmytro Leonenko
See @catwalk for a Perl 5 implementation.
rjstelling
is `<<+>>` the hovercraft operator?
Ether
+14  A: 

for Perl 5:

use List::MoreUtils 'pairwise';
@sum = pairwise { $a + $b } @arr1, @arr2;
catwalk
Doesn't work for mehttp://dpaste.com/130683/
Dmytro Leonenko
@melco-man: I thought you wanted the result to be in a reference to an array, otherwise square brackets are not needed
catwalk
Doesn't work http://dpaste.com/130684/
Dmytro Leonenko
@melco-man: don't declare my($a,$b) - they are special variables here and 'pairwise' takes care of $a and $b localization for you
catwalk
Yepp. Works!Thanks
Dmytro Leonenko
This does actually loop through both arrays, it's just hidden inside of pairwise.
Brad Gilbert
+5  A: 

Fundamentally, no, you can't do it without "looping through arrays" because you need to access every element of both arrays in order to sum them. Both the answers so far just hide the looping under a layer of abstraction but it's still there.

If you're concerned about looping over very large arrays, it's probably best to consider other ways of keeping the sum up-to-date as you go.

rjp
+2  A: 

what's wrong with looping over arrays? that's the fundamentals.

@arr1 = ( 1, 0, 0, 0, 1 );
@arr2 = ( 1, 1, 0, 1, 1 );
for ($i=0;$i<=scalar @arr1;$i++){
    print $arr[$i] + $arr2[$i] ."\n";
}
For loops? in Perl? My god man, what are you doing?
Ether
i know exactly what i am doing. I don't like to think complicated, that's all.
+4  A: 

You've seen a C style for loop, and pairwise. Here's an idiomatic Perl for loop and map:

my @arr1 = ( 1, 0, 0, 0, 1 );
my @arr2 = ( 1, 1, 0, 1, 1 );

my @for_loop;
for my $i ( 0..$#arr1 ) { 
    push @for_loop, $arr1[$i] + $arr2[$i];
}

my @map_array = map { $arr1[$_] + $arr2[$_] } 0..$#arr1;

I like map and pairwise best. I'm not sure that I have a preference between those two options. pairwise handles some boring details of plumbing for you, but it is not a built-in like map. On the other hand, the map solution is very idiomatic, and may be opaque to a part-time perler.

So, no real wins for either approach. IMO, both pairwise and map are good.

daotoad
A: 

If you're really afraid of looping, then you can binary chop the arrays, sum the pairs, then recursively reassemble the resulting array. No looping there, and as a bonus you get to learn how part of the fast-fourier transform derivation works.

parm