@array1=qw / a b c d e /;
@array2=qw / a b d e f /;
for $i ( @array1 ){
for $j ( @array2 ){
push @common, $i if $i eq $j ;
}
}
The above conventional code could be reduced as below using List::Compare
$lc = List::Compare->new(\@array1, \@array2);
@intersection = $lc->get_intersection;
@union = $lc->get_union;
List::Compare find a set of common array element by using hash referencing one of array.
The same algorithm List::Compare used could be like below
my %hash_1;
my @common;
$hash_1{$_}++ for @array1;
@common=map{ $hash_1{$_}?$_:()} @array2;
According to my benchmark test, for comparing two arrays size of 10,000, List::Compare took 0.28 sec, hash reference took 0.04 sec and conventional double for statement took 26.93 sec.
No comments:
Post a Comment