3
$\begingroup$

I want to determine whether a list A contains all the elements in the list B (including duplicate elements).

For example, for A = {1, 1, 1, 3, 3}; B = {1, 1, 1, 3, 3, 3} should return False.

For A = {1, 1, 1, 3, 3}; B = {1, 1, 1, 3} should return True.

For A = {3, 3, 1, 1, 1}; B = {1, 1, 1, 3} should return True.

For A = {3, 3, 1, 1, 4}; B = {1, 1, 4, 4} should return False.

What can I do to solve this problem succinctly?

SubsetQ[{3, 3, 1, 1, 4}, {1, 1, 4, 4}](*the result is True, which does not meet the requirements*)

In addition, I'd like to know what other ways to get the index of an array:

SeedRandom[1234]
RandomSample[Array[x, 10]]
% /. _[x_] :> x(*Besides this method, I would like to know as many methods as possible*)
$\endgroup$
4
$\begingroup$

You can use the ResourceFunction "MultisetInclusionQ":

ResourceFunction["MultisetInclusionQ"][{1,1,1,3,3},{1,1,1,3,3,3}]
ResourceFunction["MultisetInclusionQ"][{1,1,1,3,3},{1,1,1,3}]
ResourceFunction["MultisetInclusionQ"][{3,3,1,1,1},{1,1,1,3}]
ResourceFunction["MultisetInclusionQ"][{3,3,1,1,4},{1,1,4,4}]

False

True

True

False

$\endgroup$
5
$\begingroup$
ClearAll[f]
f = And @@ NonNegative[Subtract @@ (KeyUnion@(Counts /@ {##}) /. _Missing -> 0)] &;

Examples:

A1 = {1, 1, 1, 3, 3}; B1 = {1, 1, 1, 3, 3, 3};
A2 = {1, 1, 1, 3, 3}; B2 = {1, 1, 1, 3};
A3 = {3, 3, 1, 1, 1}; B3 = {1, 1, 1, 3};
A4 = {3, 3, 1, 1, 4}; B4 = {1, 1, 4, 4};

f @@@ {{A1, B1}, {A2, B2}, {A3, B3}, {A4, B4}}
{False, True, True, False}

You can also use Fold + DeleteCases as follows:

ClearAll[f2]
f2 = Fold[DeleteCases[#, #2, 1, 1] &, #2, #] === {} &;

f2 @@@ {{A1, B1}, {A2, B2}, {A3, B3}, {A4, B4}}
 {False, True, True, False}

For the second part of the question:

SeedRandom[1234]
rs = RandomSample[Array[x, 10]]
{x[1], x[7], x[5], x[6], x[9], x[3], x[10], x[4], x[8], x[2]}
rs[[All, 1]]
{1, 7, 5, 6, 9, 3, 10, 4, 8, 2}
First /@ rs
{1, 7, 5, 6, 9, 3, 10, 4, 8, 2}
$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.