# How to verify whether list A contains all elements of list B?

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*)


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

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}

test =
{{{1, 1, 1, 3, 3}, {1, 1, 1, 3, 3, 3}},
{{1, 1, 1, 3, 3}, {1, 1, 1, 3}},
{{3, 3, 1, 1, 1}, {1, 1, 1, 3}},
{{3, 3, 1, 1, 4}, {1, 1, 4, 4}}};


Define InclusionQ

InclusionQ[{a_, b_}] /; Complement[a, b] =!= {} := False

InclusionQ[{a_, b_}] :=
And @@ GreaterEqual @@@ Transpose @ Map[Tally @* Sort, {a, b}][[All, All, 2]]


Apply it

InclusionQ /@ test


{False, True, True, False}

test = {{{1, 1, 1, 3, 3}, {1, 1, 1, 3, 3, 3}}, {{1, 1, 1, 3, 3},
{1, 1, 1, 3}}, {{3, 3, 1, 1, 1}, {1, 1, 1, 3}},
{{3, 3, 1, 1, 4}, {1, 1, 4, 4}}};


Using DeleteElements to define InclusionQ:

InclusionQ[a_, b_] := DeleteElements[b, Values@# -> Keys@# &@Counts[a]] === {}

InclusionQ[#1, #2] & @@@ test

(*{False, True, True, False}*)

ContainsAll[MapIndexed[#1[#2]&,Sort[#1]],
MapIndexed[#1[#2]&,Sort[#2]]]&@@@{{A1,B1},{A2,B2},{A3,B3},{A4,B4}}

(* {False,True,True,False} *)

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};