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?
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.
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.
for Perl 5:
use List::MoreUtils 'pairwise';
@sum = pairwise { $a + $b } @arr1, @arr2;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With