Function Repository Resource:

ContainsOrderedItemsQ (1.0.0) current version: 1.0.1 »

Source Notebook

Test whether a list contains a subsequence without requiring the subsequence to be in a single sequence

Contributed by: Jon McLoone

ResourceFunction["ContainsOrderedItemsQ"][list1,list2]

returns True if the elements of list2 all occur in the same order within list1, and False otherwise.

Examples

Basic Examples (2) 

The numbers 1, 4 and 2 occur in this order in the sequence 1, 2, 3, 4, 3, 2, 1:

In[1]:=
ResourceFunction["ContainsOrderedItemsQ", ResourceVersion->"1.0.0"][{1, 2, 3, 4, 3, 2, 1}, {1, 4, 2}]
Out[1]=

The numbers 2, 1, 2 appear in the same sequence but not in this order:

In[2]:=
ResourceFunction["ContainsOrderedItemsQ", ResourceVersion->"1.0.0"][{1, 2, 3, 4, 3, 2, 1}, {2, 1, 2}]
Out[2]=

Scope (1) 

Strings are automatically converted to lists of characters:

In[3]:=
ResourceFunction["ContainsOrderedItemsQ"]["This is text", "his text"]
Out[3]=

Properties and Relations (2) 

ContainsOrderedItemsQ is different from SequenceCount and related functions because it allows the subsequence to be interrupted:

In[4]:=
ResourceFunction["ContainsOrderedItemsQ"][{1, 2, 3, 4, 5}, {1, 2}]
Out[4]=
In[5]:=
ResourceFunction["ContainsOrderedItemsQ"][{1, 2, 3, 4, 5}, {1, 5}]
Out[5]=

SequenceCount, on the other hand, requires the sequence to be together:

In[6]:=
SequenceCount[{1, 2, 3, 4, 5}, {1, 2}]
Out[6]=
In[7]:=
SequenceCount[{1, 2, 3, 4, 5}, {1, 5}]
Out[7]=

Publisher

Jon McLoone

Version History

  • 1.0.1 – 13 March 2024
  • 1.0.0 – 13 March 2023

License Information