Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Compare arrays remove identical

by cdherold (Monk)
on May 02, 2001 at 01:15 UTC ( [id://77133]=perlquestion: print w/replies, xml ) Need Help??

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

fellow monks,

I have two array's ... @kansas and @oklahoma. I want to compare the two arrays, determine identical content and then remove that content from @kansas.

The problem (for me) is how to find identical content.

Once I find the identical content I intend to remove it using splice() function.

Any ideas on how to get the identical content between the two arrays?

thanks

Replies are listed 'Best First'.
Re: Compare arrays remove identical
by wardk (Deacon) on May 02, 2001 at 01:24 UTC
Re: Compare arrays remove identical
by perlmonkey (Hermit) on May 02, 2001 at 11:26 UTC
    Theres a section in Mastering Algorithms with Perl on sets also. If you need a full implementation of unions/differences/intersections etc see the Set::Scalar module. If you use chromatic's code linked to above, I gave into my compulsion to do a tiny bit of benchmarking:
    my @kansas = qw( corn wheat hay cattle ); my @oklahoma = qw( wheat dairy cattle ); use Benchmark; timethese(100000, { "diff1" => sub { diff1(\@kansas, \@oklahoma) }, "diff2" => sub { diff2(\@kansas, \@oklahoma) }, }); sub diff1 { my %hash; @hash{@{$_[1]}} = (1) x @{$_[1]}; return grep { !defined $hash{$_} } @{$_[0]}; } sub diff2 { my %hash = map{ $_=>1} @{$_[1]}; return grep { !defined $hash{$_} } @{$_[0]}; }
    It seems that a hash slice is a teeny bit faster than map for this purpose:
    Results:
    Benchmark: timing 100000 iterations of diff1, diff2... diff1: 2 wallclock secs ( 1.74 usr + 0.01 sys = 1.75 CPU) diff2: 3 wallclock secs ( 2.22 usr + 0.01 sys = 2.23 CPU)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (7)
As of 2024-04-25 15:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found