Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Getting the intersection of n collections.

by GrandFather (Sage)
on Oct 12, 2006 at 07:59 UTC ( #577772=note: print w/ replies, xml ) Need Help??


in reply to Getting the intersection of n collections.

List::Compare is the tool generally used for this sort of thing:

use strict; use warnings; use List::Compare; my @AllArraysIHave = ([1,2,3,4,5], [2,3,6,7,8,8,8,9,10], [5,6,2,3]); my $lc = List::Compare->new('-u', @AllArraysIHave); my @result = $lc->get_intersection; print "@result";

Prints:

3 2

Update: speed is disapointing though (listCompareF use the functional interface):

manual: 3 2 listCompareF: 2 3 listCompare: 3 2 Rate listCompare listCompareF manual listCompare 1128/s -- -70% -93% listCompareF 3822/s 239% -- -78% manual 17051/s 1411% 346% --
use strict; use warnings; use List::Compare; use List::Compare::Functional qw(get_intersection); use Benchmark qw(cmpthese); my @AllArraysIHave = ([1,2,3,4,5], [2,3,6,7,8,8,8,9,10], [5,6,2,3]); my @result = @{manual ()}; print "manual: @result\n"; @result = @{listCompareF ()}; print "listCompareF: @result\n"; @result = @{listCompare ()}; print "listCompare: @result\n"; cmpthese (-1, { manual => \&manual, listCompare => \&listCompare, listCompareF => \&listCompareF, } ); sub manual { my %intersection; my @result; foreach my $dataArray(@AllArraysIHave) { my %lookuptable; foreach(@{$dataArray}) { if (!$lookuptable{$_}) { $lookuptable{$_} = 1; $intersection{$_}++; } } } my $amnt = scalar(@AllArraysIHave); foreach my $key (keys %intersection) { if ($intersection{$key} == $amnt) { push @result, $key; } } return \@result; } sub listCompare { my $lc = List::Compare->new('-u', @AllArraysIHave); my @result = $lc->get_intersection; return \@result; } sub listCompareF { my @result = get_intersection ([@AllArraysIHave]); return \@result; }

DWIM is Perl's answer to Gödel


Comment on Re: Getting the intersection of n collections.
Select or Download Code
Re^2: Getting the intersection of n collections.
by Anonymous Monk on Oct 12, 2006 at 09:41 UTC
    That's because List::Compare calculates lots of things you aren't interested in. It's doing them from new.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://577772]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2015-07-05 08:12 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (61 votes), past polls