Front page | perl.beginners | Postings from February 2009

## Re: How to speed up two arrays compare.

From:
Rob Dixon
Date:
February 11, 2009 05:47
Subject:
Re: How to speed up two arrays compare.
Message ID:
4992D6FF.4000304@gmx.com
```kevin liu wrote:
> Hi everybody:
>
>         I have two arrays(@nwarray0 and @nwarray1) in my program and i want
> to make sure that
> all the elements in @nwarray0 could be found in @nwarray1.
>         Here is my implementation:
>         -------------------------------------------------------
>         foreach my \$srctemp ( @nwarray0 ) {
>
>             foreach my \$tgttemp ( @nwarray1 ) {
>                 if ( \$tgttemp eq \$srctemp ) {
>                     \$found = 1;
>                     last;
>                 }
>             }
>             if ( \$found == 1 ) {
>                 \$found = 0;
>                 next;
>             }
>             else {
>                 return 1;
>             }
>         }
>         --------------------------------------------------------
>         But this algorithm takes a long time to compare, could you please
> help to improve this piece of
> code to less the time needed?

The classical method is to use a hash, but there is also a module List::Compare
that is written to do this kind of job for you. The program below illustrates
both methods.

HTH,

Rob

use strict;
use warnings;

use List::Compare;

# Using List::Compare
#
my @nwarray0 = qw/A B C D/;
my @nwarray1 = qw/A B D E F G/;

my \$compare = List::Compare->new(\@nwarray0, \@nwarray1);

my @unique = \$compare->get_unique;
print scalar @unique, " unique keys in @nwarray0\n";

# Using a hash
#
my %unique;

@unique{@nwarray0} = ();
delete @unique{@nwarray1};

print scalar keys %unique, " unique keys in @nwarray0\n";

```