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)  (x1)(x))/2
Hopefully it will be handy to know that some day :)
* or had forgotten.
