Function Repository Resource:

FindRanges

Source Notebook

Find continuous ranges in a list of integers

Contributed by: Jan Pöschko (Wolfram Research)

ResourceFunction["FindRanges"][list]

returns ranges of consecutive values for the integers in list.

Details and Options

The given list is sorted before detecting ranges.
The returned ranges are in ascending order.

Examples

Basic Examples (1) 

Find ranges of consecutive values in a list of integers:

In[1]:=
ResourceFunction["FindRanges"][{1, 2, 3, 5, 6, 8}]
Out[1]=

Scope (1) 

The given list does not need to be sorted, but will be sorted automatically:

In[2]:=
ResourceFunction["FindRanges"][{2, 8, 3, 1, 5, 6}]
Out[2]=

Properties and Relations (1) 

The returned ranges can be joined into the original set of numbers again:

In[3]:=
list = RandomInteger[100, 50]
Out[3]=
In[4]:=
ranges = ResourceFunction["FindRanges"][list]
Out[4]=
In[5]:=
joined = Join @@ Range @@@ ranges
Out[5]=
In[6]:=
joined == Union[list]
Out[6]=

Possible Issues (2) 

Noninteger numbers are "swallowed" if they are between consecutive integers in the list:

In[7]:=
ResourceFunction["FindRanges"][{1, 1.5, 2, 3.2, 4, 8.3}]
Out[7]=

Expressions that are not integers or real numbers each constitute their own "range":

In[8]:=
ResourceFunction["FindRanges"][{1, 2, x, y, "str"}]
Out[8]=

Publisher

Jan Poschko

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 04 February 2019

License Information