王云龙
王云龙

Reputation: 71

Perl How to traverse and compare all the elements inside two different array in a faster way?

Assume there are two arrays, each of them holding very large number of elements. Now I want to compare every each element inside both, if I just do like usual way: using two nested for loop to do the job, it would be quite time consuming. Are there any faster workaround to achieve same purposes? Thanks!

Upvotes: 0

Views: 121

Answers (1)

ikegami
ikegami

Reputation: 385655

The trick is to speed up lookups, say, by using a hash.

Depending on the specifics, some variation of the following could be used:

my %array1;
++$array1{$_} for @array1;
for (@array1) {
   say "$_ isn't in \@array1"
      if !$array1{$_};
}

If duplicates are possible:

my %array1;
++$array1{$_} for @array1;
my %array2;
for (@array1) {
   say "$_ isn't in \@array1"
      if ++$array2{$_} > ($array1{$_} // 0);
}

Upvotes: 1

Related Questions