Function Repository Resource:

IncreasingFilter

Source Notebook

Filter a list, keeping only increasing values

Contributed by: Sander Huisman

ResourceFunction["IncreasingFilter"][list]

filters list by only selecting increasing values.

ResourceFunction["IncreasingFilter"][list,p]

filters list using the ordering function p.

Details and Options

ResourceFunction["IncreasingFilter"] scans the list of items in order. After the first item, which is retained, subsequent items are only retained if they are not smaller than their predecessors.
ResourceFunction["IncreasingFilter"] is an O(n) algorithm.
The result of ResourceFunction["IncreasingFilter"] is sorted in ascending order according to the ordering function p.
The output of ResourceFunction["IncreasingFilter"] does not generally have the same length as the input.
The option "StrictlyIncreasing" (default False) can be switched to True to not retain duplicates.
ResourceFunction["IncreasingFilter"] is also known as Stalin sort.

Examples

Basic Examples (2) 

Only retain the increasing values of a list:

In[1]:=
ResourceFunction["IncreasingFilter"][{1, 1, 2, 4, 3, 7, 2, 7, 9}]
Out[1]=

Filter another list:

In[2]:=
ResourceFunction["IncreasingFilter"][{7, 8, 9, 10, 9, 8, 7, 6, 5, 4}]
Out[2]=

Scope (4) 

Use a different ordering function p:

In[3]:=
{
 ResourceFunction["IncreasingFilter"][{Sqrt[2], 2, Pi}],
 ResourceFunction["IncreasingFilter"][{Sqrt[2], 2, Pi}, NumericalOrder]
 }
Out[3]=

Apply it to strings using the ordering function AlphabeticOrder:

In[4]:=
ResourceFunction[
 "IncreasingFilter"][{"a", "b", "d", "c", "b", "f", "b"}, AlphabeticOrder]
Out[4]=

Filter with decreasing values:

In[5]:=
ResourceFunction["IncreasingFilter"][{8, 10, 9, 8, 7, 6, 5, 7, 2}, Order[#2, #1] &]
Out[5]=

Do not allow for repeated items making a strictly increasing sequence:

In[6]:=
ResourceFunction[
 "IncreasingFilter"][{1, 1, 2, 2, 3, 3, 4, 5, 6, 3, 2, 1}, Order, "StrictlyIncreasing" -> True]
Out[6]=

Properties and Relations (3) 

An empty list as input just returns an empty list:

In[7]:=
ResourceFunction["IncreasingFilter"][{}]
Out[7]=

A single element stays a single element:

In[8]:=
ResourceFunction["IncreasingFilter"][{1}]
Out[8]=

IncreasingFilter is idempotent:

In[9]:=
ResourceFunction[
  "IncreasingFilter"][{4, 6, 2, 3, 1, 6, 9, 2, 5, 2, 10, 3}] === ResourceFunction["IncreasingFilter"][
  ResourceFunction[
   "IncreasingFilter"][{4, 6, 2, 3, 1, 6, 9, 2, 5, 2, 10, 3}]]
Out[9]=

The input and output do not necessarily have the same length:

In[10]:=
in = {2, 6, 3, 8, 3, 9, 1};
Length[ResourceFunction["IncreasingFilter"][in]] != Length[in]
Out[11]=

Publisher

SHuisman

Requirements

Wolfram Language 13.0 (December 2021) or above

Version History

  • 1.0.0 – 19 April 2024

Related Resources

License Information