in reply to Difference between two arrays

I think this is a little different approach. Since the original array was in ascending order to find the swapped elements we just need to find the descending step in the $after array. Once you have the location, you just need to determine if it moved right or left.
my $after = [qw(2 3 4 1 5 6 7 8 9 10)]; for (my $i = 1; $i < scalar($after); $i++){ my $diff = after->[$i-1] - $after->[$i]; if($diff > 0){ if($diff > $i){ printf "$after->[$i-1] moved to position %d\n",($i-1); } else{ print "$after->[$i] moved to position $i\n"; } last; } }
The output would be:
1 moved to position 3

Replies are listed 'Best First'.
Re^2: Difference between two arrays
by Anonymous Monk on Mar 23, 2006 at 05:36 UTC
    This will work only for the elements which are removed in the front.
    my $before = [qw(1 2 3 4 5 6 7 8 9 10)]; my $after = [qw(1 2 4 3 5 6 7 8 9 10)]; $k=0; for($i=0;$i<=@$before;$i++) { for($j=$k;$j<=@$after;$j++) { if(@$before[$i] eq @$after[$j] and $i==$j) { $i++;$k++; } if(@$before[$i] eq @$after[$j] and $i!=$j) { print "element @$before[$i] is moved to the position ",$j ++1; $i=@$before+1; last; } } } __DATA__ element 3 is moved to the position 4
    Any comments to this code.