Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: how do i find common elements of X number of arrays whose names i don't know?

by integral (Hermit)
on Jun 28, 2004 at 08:10 UTC ( #370139=note: print w/ replies, xml ) Need Help??


in reply to how do i find common elements of X number of arrays whose names i don't know?

Firstly to find @accessors, you can use the keys function on the %$self hash.

But I'd choose to push the value rather than the key so a loop over values(%$self) might make more sense.

my @tocheck; for my $value (values %$self) { push @tocheck, $value if ref($value) eq 'ARRAY'; } my %seen; for my $array (@tocheck) { $seen{$_}++ for @$array; } return grep { $seen{$_} == @tocheck } keys %seen;

So far we haven't used map (but we did use grep), but we can combine the two loops together so we don't need @tocheck as an intermediate.

my ($n, %seen); for my $array (values %$self) { next unless ref($array) eq 'ARRAY'; # we're only interested in array +s $seen{$_}++ for @$array; $n++; } return grep { $seen{$_} == $n } keys %seen;

Here's a solution using map to replace one of the loops (Update: But it doesn't solve the right problem, since it just checks for duplicates, rather than things appearing multiple times):

my %seen; for my $value ( map { ref($_) eq 'ARRAY' ? @$_ : () } values %$self ) +{ $seen{$value}++; } return grep { $seen{$_} > 1 } keys %seen;

--
integral, resident of freenode's #perl


Comment on Re: how do i find common elements of X number of arrays whose names i don't know?
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (13)
As of 2014-09-19 20:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (146 votes), past polls