- How do I compute the difference of two arrays? How do I compute the intersection of two arrays?
Use a hash. Here's code to do both and more. It assumes that each element is unique in a given array:
sub difference {
my ( @array1, @array2 ) = ( @{$_[0]}, @{$_[1]} );
my @difference = (); my @intersection = 0;
my %count = ();
foreach my $element (@array1, @array2) { $count{$element}++ }
foreach my $element (keys %count) {
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}
return \@difference;
}
Hide Comments