Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - determine if an array is a subset of another array [duplicate]

Tags:

perl

I have the following code. Can isSubset be written simpler without add-on CPAN modules?

my @possibleNames = ("adam", "chelsea");
my @actualNames = ("adam", "chucky", "chelsea");

sub isSubset {
    my ($littleSet, $bigSet) = @_;
    foreach (@{$littleSet}) {
        return 0 unless ($_ ~~ @{$bigSet});
    }
    return 1;
}

printf("%s\n", (isSubset(\@possibleNames, \@actualNames) ? "yes" : "no"));
like image 600
Adam S Avatar asked Jun 05 '13 18:06

Adam S


People also ask

How do you check if an array is subset of another array?

Naive Approach to Find whether an array is subset of another array. Use two loops: The outer loop picks all the elements of arr2[] one by one. The inner loop linearly searches for the element picked by the outer loop. If all elements are found then return 1, else return 0.

What is subset of an array?

An array B is a subset of another array A if each element of B is present in A. ( There are no repeated elements in both the arrays) For example. input : A[] = { 3, 5, 7, 12, 1, 9, 10, 0, 2 }, B[] = { 1, 3, 5, 9 }


2 Answers

One fairly efficient way to do it would be:

sub isSubset {
    my ($littleSet, $bigSet) = @_;
    my %hash;
    undef @hash{@$littleSet};  # add a hash key for each element of @$littleSet
    delete @hash{@$bigSet};    # remove all keys for elements of @$bigSet
    return !%hash;             # return false if any keys are left in the hash
}
like image 155
Ilmari Karonen Avatar answered Sep 20 '22 23:09

Ilmari Karonen


my @possibleNames = ("adam", "chelsea");
my @actualNames = ("adam", "chucky", "chelsea");

my $is_subset = 0==grep !defined, map { @$_{@actualNames}=(1)x@actualNames; delete @$_{@possibleNames} } {};

But seriously, use Array::Utils::array_minus.

like image 44
ysth Avatar answered Sep 19 '22 23:09

ysth