Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

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

by Anonymous Monk
on Jun 30, 2000 at 11:56 UTC ( [id://20553]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

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

Originally posted as a Categorized Question.

  • Comment on How do I pick anything that is in array A that is NOT in array B

Replies are listed 'Best First'.
Re: How do I pick anything that is in array A that is NOT in array B
by Anonymous Monk on Jun 30, 2000 at 12:20 UTC
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
    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";

      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: perlquestion [id://20553]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2024-04-19 23:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found