Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: How do I pick anything that is in array A that is NOT in array B

by gansi (Initiate)
on Jan 27, 2010 at 09:51 UTC ( [id://819879]=note: print w/replies, xml ) Need Help??


in reply to How do I pick anything that is in array A that is NOT in array B

use strict; my @A = (2..5); my @B = (4..7); my @A_not_B; foreach my $data ( @A ) { push @A_not_B, $data unless grep { $_ eq $data } @B; } print "FINAL :: @A_not_B \n";
  • Comment on Re: How do I pick anything that is in array A that is NOT in array B
  • Download Code

Replies are listed 'Best First'.
Re: Answer: How do I pick anything that is in array A that is NOT in array B
by MidLifeXis (Monsignor) on Jan 27, 2010 at 16:55 UTC

    This is O(N*M) (where N is sizeof A, and M is sizeof B). You can do it in O(N+M) by building a hash with the contents of B, and using that for your test (instead of grep).

    my %B = map { $_ => 1 } @B; foreach my $data ( @A ) { push @A_not_B, $data unless $B{$data}; }

    You could also replace the foreach loop with:

    @A_not_B = grep { ! $B{$_} } @A;

    If N and M are large, the difference between O(N+M) and O(N*M) can be substantial. For the sample set, it is probably not noticeable.

    It is said that "only perl can parse Perl." I don't even come close until my 3rd cup of coffee. --MidLifeXis

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://819879]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2024-04-18 15:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found