in reply to Is one array a subset of the other

As soon as you're thinking of "sets" of unique items and not particularly interested in their order, use hashes.

Untested.

my %a1; @a1{qw(a b c d e f g)} = (); my %a2; @a2{qw(b g)} = (); my @a1only = grep { not exists $a2{$_} } keys %a1; my @a2only = grep { not exists $a1{$_} } keys %a2; my @both = grep { exists $a2{$_} } keys %a1; my %u; my @either = grep { not $u{$_}++ } (keys %a1, keys %a2); # your question: print "subset" if not @a2only;

--
[ e d @ h a l l e y . c c ]

Replies are listed 'Best First'.
Re: Re: Is one array a subset of the other
by pzbagel (Chaplain) on May 19, 2003 at 20:10 UTC

    Why all the hashes? Array lookups are faster, no? Plus this way you have no extra arrays hanging around. First argument to issubset() is a ref to the big set, second argument is a ref the alleged subset:

    #!/usr/bin/perl use strict; my @a1=qw(a b c d e f g); my @a2=qw(b g); my @a3=qw(c d e f g h); sub issubset { ($a,$b)=@_; for my $x (@$b) { return ("not a subset") unless grep {$x eq $_} @$a; } return ("a subset"); } print "a2 is ",issubset(\@a1,\@a2)," of a1\n"; print "a3 is ",issubset(\@a1,\@a3)," of a1\n"; __END__ Output is: a2 is a subset of a1 a3 is not a subset of a1

    HTH

      Array "lookups" are not faster than hash key lookups. That's the point. It's always O(1) {always takes the same amount of time, regardless of set size} to detect the presence of a key in a hash, while it's O(N) {grows linearly slower as you have more elements} to detect the presence of an element in an array.

      --
      [ e d @ h a l l e y . c c ]