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"));
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.
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 }
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With