### Re: Difference between two arrays

by unobe (Scribe)
 on Mar 23, 2006 at 11:28 UTC ( #538716=note: print w/replies, xml ) Need Help??

in reply to Difference between two arrays

I actually got really interested in this problem and thought of trying to use a mathematical formula for what the sum of a sequential numbers is. Anyway, I came up with a solution which I think is elegant, and which uses what I discovered:
```use strict;
use warnings;

my @orig = (1..10);
my @altered = ( [qw( 1  2  3  4  9  5  6  7  8 10)],
[qw( 2  3  4  1  5  6  7  8  9 10)],
[qw( 1  2  3  4 10  5  6  7  8  9)],
[qw( 1  2  3  5  4  6  7  8  9 10)],
[qw( 1  3  4  5  6  7  2  8  9 10)],
[qw( 1  2  3  4  5  6  7  8 10  9)],
[qw( 1  2  3  4  6  5  7  8  9 10)],
);

for my \$test (@altered) {
my %count = ();
my (\$val, \$flag) = (undef, \$orig[0] == \$test->[0]);

for my \$i (0..\$#orig) {
# keep track of what the nums in each array add up to
\$count{before} += \$orig[\$i];
\$count{after}  += \$test->[\$i];

if ((\$flag && (\$count{before} != \$count{after}))
|| (!\$flag && (\$count{before} == \$count{after}))) {
\$val = ( \$test->[\$i] == \$orig[\$i+1])
? \$orig[\$i]
: \$test->[\$i];
last;
}
}
print "\$val moved between (@orig) and (@\$test)\n";
}

Basically, if the first numbers of each array are equal, look for when the array sums aren't equal. If the first numbers of each array aren't equal, look for when the array sums are equal. There's a special case in there (hence the ternary operator), but I can't explain it really. (Anyone else know why?) The last test case is ambiguous, since 5 and 6 are transposed and either (depending on if you're scanning left to right or right to left) could be said to have moved (this solution says 6 has moved). I actually really enjoyed doing this problem because I figured out something I didn't know before (in terms of math)*:
```The sum of a sequence of integers from x to x+n equals
((x+n)(x+n+1) - (x-1)(x))/2
Hopefully it will be handy to know that some day :-)

Create A New User
Node Status?
node history
Node Type: note [id://538716]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2017-08-19 13:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Who is your favorite scientist and why?

Results (311 votes). Check out past polls.

Notices?