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;
@uniq...@nwarray0} = ();
delete @uniq...@nwarray1};
print scalar keys %unique, " unique keys in @nwarray0\n";
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/