in reply to intersection of N arrays

my $numArrays = keys %ids; my %count = (); my @intersection = (); foreach my $k (keys %ids) { my %uniq = map { $_ => 1 } @{ $ids{$k} }; $count[$_]++ for keys %uniq; } foreach my $v (keys %count) { push @intersection, $v if $count[$v] == $numArrays; }
Some one can golf that I'm sure.. That's a real quick first pass.. Do you understand what its doing? If not, I can explain! :)

You might also want to check out the CPAN for cool modules like Quantum::Superpositions or just seek and you might find.

Update: Fixed solution such that multiple occurences in a single array won't skew the results per Solo's post.

-brad..

Replies are listed 'Best First'.
Re^2: intersection of N arrays
by Solo (Deacon) on Jul 01, 2004 at 02:51 UTC
    Wouldn't this fail if the same element appears mulitple times in an array, such that the number of times it appears overall is == num of arrays? This code assumes all elements are unique in each array.

    The next solution has the same assumption.

    A quick look at the source of List::Compare leads me to think it does not make that assumption.

    --Solo
    --
    You said you wanted to be around when I made a mistake; well, this could be it, sweetheart.
      Wouldn't this fail if the same element appears mulitple times in an array, such that the number of times it appears overall is == num of arrays? This code assumes all elements are unique in each array.

      The provided code does not make that assumption. The key lines are:

      foreach my $k (keys %ids) { my %uniq = map { $_ => 1 } @{ $ids{$k} }; $count[$_]++ for keys %uniq; }
      If the array in $ids{$k} has a whole bunch of 1s in it, that's okay, we'll overwrite $uniq{1} a whole bunch of times. Because hash keys must be unique.

      This means that at the last statement in this loop %uniq will represent a hash with only the unique values from $ids{$k}

      I hope this helps.

      jarich

Re^2: intersection of N arrays
by nkuitse (Sexton) on Jul 02, 2004 at 14:58 UTC
    A slight improvement...
    sub intersection { my $n = scalar @_; my %count; foreach my $list (@_) { my %elements = map { $_ => 1 } @$list; $count{$_}++ foreach keys %elements; } return [ grep { $count{$_} == $n } keys %count ]; }