in reply to Difference arrays.
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Difference arrays.
by ikegami (Patriarch) on Sep 05, 2008 at 05:44 UTC | |
by mr_mischief (Monsignor) on Sep 05, 2008 at 09:48 UTC | |
by ikegami (Patriarch) on Sep 05, 2008 at 22:12 UTC |