How do I calculate the difference between each element in two arrays?

1.1k Views Asked by At

I have a text file with numbers which I have grouped as follows, seperated by blank line:

42.034 41.630 40.158 26.823 26.366 25.289 23.949

34.712 35.133 35.185 35.577 28.463 28.412 30.831

33.490 33.839 32.059 32.072 33.425 33.349 34.709

12.596 13.332 12.810 13.329 13.329 13.569 11.418

Note: the groups are always of equal length and can be arranged in more than one line long, if the group is large, say 500 numbers long. I was thinking of putting the groups in arrays and iterate along the length of the file.

My first question is: how should I subtract the first element of array 2 from array 1, array 3 from array 2, similarly for the second element and so on till the end of the group?

i.e.:

34.712-42.034,35.133-41.630,35.185-40.158 ...till the end of each group

33.490-34.712,33.839-35.133   ..................

and then save the differences of the first element in one group (second question: how ?) till the end

i.e.:

34.712-42.034 ; 33.490-34.712 ; and so on in one group

35.133-41.630 ; 33.839-35.133 ; ........

I am a beginner so any suggestions would be helpful.

2

There are 2 best solutions below

2
On

Assuming you have your file opened, the following is a quick sketch

use List::MoreUtils qw<pairwise>;
...

my @list1 = split ' ', <$file_handle>;
my @list2 = split ' ', <$file_handle>;

my @diff  = pairwise { $a - $b } @list1, @list2;

pairwise is the simplest way.

Otherwise there is the old standby:

# construct a list using each index in @list1 ( 0..$#list1 )
# consisting of the difference at each slot.
my @diff = map { $list1[$_] - $list2[$_] } 0..$#list1;
0
On

Here's the rest of the infrastructure to make Axeman's code work:

#!/usr/bin/perl
use strict;
use warnings;
use List::MoreUtils qw<pairwise>;

my (@prev_line, @this_line, @diff);
while (<>) {
    next if /^\s+$/; # skip leading blank lines, if any
    @prev_line = split;
    last;
}

# get the rest of the lines, calculating and printing the difference,
# then saving this line's values in the previous line's values for the next
# set of differences
while (<>) {
    next if /^\s+$/; # skip embedded blank lines

    @this_line = split;
    @diff      = pairwise { $a - $b } @this_line, @prev_line;

    print join(" ; ", @diff), "\n\n";

    @prev_line = @this_line;
}

So given the input:

1 1 1

3 2 1

2 2 2

You'll get:

2 ; 1 ; 0

-1 ; 0 ; 1