Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sum arrays element-wise in Perl?

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?

like image 532
Dmytro Leonenko Avatar asked Dec 08 '09 09:12

Dmytro Leonenko


People also ask

How do you sum two arrays?

The idea is to start traversing both the array simultaneously from the end until we reach the 0th index of either of the array. While traversing each elements of array, add element of both the array and carry from the previous sum. Now store the unit digit of the sum and forward carry for the next index sum.

How do I add an element to an array in Perl?

Perl offers many useful functions to manipulate arrays and their elements: push(@array, element) : add element or elements into the end of the array. $popped = pop(@array) : delete and return the last element of the array. $shifted = shift(@array) : delete and return the first element of the array.


2 Answers

for Perl 5:

use List::MoreUtils 'pairwise';
@sum = pairwise { $a + $b } @arr1, @arr2;
like image 131
catwalk Avatar answered Oct 13 '22 21:10

catwalk


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.

like image 22
Richard Stelling Avatar answered Oct 13 '22 22:10

Richard Stelling