2
$\begingroup$

Suppose I have a ordered set $A=\{2,3\}$ and $B=\{2,3,4\}$ and $C=\{2,4,3\}$. Is there any mathematica command whether $A\subset B$ gives true(or 1) but $A$ which is not a subset of $C$ gives false(or 0)?

I know OrderedQ, but that only gives OrderedQ[{2, 3}] == True and OrderedQ[{3, 2}] == False, so it was not that useful.

$\endgroup$

1 Answer 1

2
$\begingroup$
ClearAll[subsequenceQ]
subsequenceQ = MemberQ[Subsequences[#2, Length @ #], #] &;

Examples:

a = {2, 3} ; b = {2, 3, 4} ; c = {2, 4, 3};

subsequenceQ[a, b]
True
subsequenceQ[a, c]
False
subsequenceQ[a, {4, 2, 3, 5}]
True

Alternatively, you can use:

ClearAll[subsequenceQ1, subsequenceQ2, subsequenceQ3]

subsequenceQ1 = MemberQ[Partition[#2, Length@#, 1], #] &;

subsequenceQ2 = MatchQ[#2, Flatten[{___, #, ___}]] &;

subsequenceQ3 = SequenceCases[#2, #] =!= {} &;
$\endgroup$
3
  • 1
    $\begingroup$ Wow good! Thanks today, I learn many things on mathematica from your answer! $\endgroup$
    – phy_math
    Mar 16, 2021 at 6:58
  • $\begingroup$ @phy_math, my pleasure. Thank you for the accept. Welcome to mma.se. $\endgroup$
    – kglr
    Mar 16, 2021 at 7:02
  • $\begingroup$ What if I allow the order. I mean $\{2,3\}$ is in $\{2,5,4,3\}$. Then How I can modify your function? I post another question with a specific example $\endgroup$
    – phy_math
    Mar 16, 2021 at 7:54

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.