[plug] Perl: Intersection of two arrays?
Simon Newton
newtons at iinet.net
Wed Jun 25 15:18:23 WST 2003
> Here's the routine I ended up going with:
>
> sub SetIntersection($$)
> {
> my ($set1,$set2) = @_;
> my %count = ();
> my $element;
> foreach $element (@{$set1}) { $count{$element} |= 1; };
> foreach $element (@{$set2}) { $count{$element} |= 2; };
> return grep { $count{$_} == 3 } keys %count;
> }
you could shorten it a bit:
sub SetIntersection
{
my %count = ();
foreach (@{$_[0]}) { $count{$_} |= 1; };
foreach (@{$_[1]}) { $count{$_} |= 2; };
return grep { $count{$_} == 3 } keys %count;
}
at the expense of becomming unreadable :)
> I still wonder if a custom function written in C could do things a chunk
> faster. ^_^
If you really wanted speed, you wouldn't be using Perl.
You might want to take a look at Inline::C . I've never used it but I'd
say its what your after.
Simon N
More information about the plug
mailing list