This version assumes one can modify @a for even a bit more memory savings:
outputs: 42, 42, 43, 43, 44, 46my @a = ( 42, 42, 43, 43, 43, 44, 45, 46 ); my @b = ( 43, 45 ); for my $i ( 0 .. $#b ) { for my $j ( 0 .. $#a ) { next unless defined $a[ $j ]; $a[ $j ] = undef, last if $a[ $j ] == $b[ $i ]; } } @a = grep { defined } @a; print join ', ', @a; print "\n";
This obviously trivial modification is more conservative and assumes one can't modify @a:
my @a = ( 42, 42, 43, 43, 43, 44, 45, 46 ); my @b = ( 43, 45 ); my @c = @a; for my $i ( 0 .. $#b ) { for my $j ( 0 .. $#c ) { next unless defined $c[ $j ]; $c[ $j ] = undef, last if $c[ $j ] == $b[ $i ]; } } @c = grep { defined } @c; print join ', ', @c; print "\n";
The second outputs the same as the first. Neither cares if the arrays are presorted, because it's O(m*n) and checking each against each already.
In reply to Re: Difference arrays.
by mr_mischief
in thread Difference arrays.
by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |