Wolfram Research

Function Repository Resource:

RotateLeftUntil

Source Notebook

Cycle the elements of a list to the left until a criterion is satisfied

Contributed by: Sander Huisman

ResourceFunction["RotateLeftUntil"][expr,crit]

cycles the elements in expr positions to the left until the first element satisfies crit.

ResourceFunction["RotateLeftUntil"][expr,crit,n]

cycles the elements in expr positions until crit has been satisfied n times.

ResourceFunction["RotateLeftUntil"][expr,crit,n,m]

cycles the elements in expr positions until crit has been satisfied n times with at most m iterations.

Details and Options

ResourceFunction["RotateLeftUntil"] is generally used to bring a certain element to the front.
The default value of n is 1.
When n is 0, the original expr is returned.
m is by default set to n×Length[expr].
$Failed is returned if n fulfillments cannot be found in m iterations.

Examples

Basic Examples

Put the element "e" in front:

In[1]:=
ResourceFunction["RotateLeftUntil"][{"a", "d", "e", "c", "b", "x"}, EqualTo["e"]]
Out[1]=

Rotate until the fourth prime is in front:

In[2]:=
ResourceFunction["RotateLeftUntil"][Range[20], PrimeQ, 4]
Out[2]=

Scope

Rotate until the first 5 is in front:

In[3]:=
ResourceFunction[
 "RotateLeftUntil"][{1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 10}, EqualTo[5]]
Out[3]=

Rotate until a value greater than or equal to 4 has been seen three times:

In[4]:=
ResourceFunction[
 "RotateLeftUntil"][{1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 10}, GreaterEqualThan[4], 3]
Out[4]=

Find the seventh occurrence of a value between 5 and 7, with a maximum of one hundred iterations:

In[5]:=
ResourceFunction[
 "RotateLeftUntil"][{1, 2, 3, 4, 5, 6, 7, 8, 9, 5, 10}, Between[{5, 7}], 7, 100]
Out[5]=

Applications

Rotate the letters until a capital letter is at the front:

In[6]:=
ResourceFunction["RotateLeftUntil"][
 Characters["my name is Alejandro."], UpperCaseQ]
Out[6]=

Properties and Relations

RotateLeftUntil is related to RotateLeft and Position:

In[7]:=
list = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
{
 ResourceFunction["RotateLeftUntil"][list, EqualTo[15]],
 RotateLeft[list, FirstPosition[list, 15] - 1]
 }
Out[8]=

Possible Issues

If the condition is not fulfilled within a cycle, $Failed is returned:

In[9]:=
ResourceFunction["RotateLeftUntil"][{"a", "d", "e", "c", "b", "x"}, EqualTo["g"]]
Out[9]=

For crit that change, more than n cycles might be needed:

In[10]:=
ResourceFunction["RotateLeftUntil"][
 Range[10], (EqualTo[RandomInteger[{1, 100}]][#]) &, 3]
Out[10]=

Increase the maximum number of iterations:

In[11]:=
ResourceFunction["RotateLeftUntil"][
 Range[10], (EqualTo[RandomInteger[{1, 100}]][#]) &, 3, \[Infinity]]
Out[11]=

Resource History

License Information