Function Repository Resource:

SelectTuples

Source Notebook

Generate tuples that satisfy a certain criterion

Contributed by: Sander Huisman

ResourceFunction["SelectTuples"][list,n,crit]

generates a list of n‐tuples of elements from list that satisfy crit.

ResourceFunction["SelectTuples"][{list1,list2,},crit]

generates a list of all possible tuples whose ith element is from listi that satisfy crit.

ResourceFunction["SelectTuples"][,crit,m]

picks at most the first m tuples that satisfy crit.

Details and Options

ResourceFunction["SelectTuples"] is used in cases for which generating all tuples would be too memory intensive, especially when the elements of list are large and the number of tuples that satisfy crit is small.
ResourceFunction["SelectTuples"] is an alternative to Select[Tuples[],crit], which first generates all tuples.

Examples

Basic Examples (2) 

Find out which 2-tuples have a sum that is prime:

In[1]:=
ResourceFunction["SelectTuples"][Range[10], 2, PrimeQ@*Total]
Out[1]=

Get the first five such 2-tuples:

In[2]:=
ResourceFunction["SelectTuples"][Range[10], 2, PrimeQ@*Total, 5]
Out[2]=

Scope (1) 

Find the first 15 three-letter palindromic lists:

In[3]:=
ResourceFunction["SelectTuples"][CharacterRange["a", "e"], 3, PalindromeQ@*StringJoin, 15]
Out[3]=

Applications (1) 

Find vectors for which the norm is an integer:

In[4]:=
ResourceFunction["SelectTuples"][Range[-100, 100], 2, IntegerQ@*Norm] // Point // Graphics
Out[4]=

Properties and Relations (2) 

The main difference between Select and Tuples and SelectTuples is the amount of memory used:

In[5]:=
MaxMemoryUsed[
 ResourceFunction["SelectTuples"][Range[10], 5, EqualTo[30]@*Total]]
Out[5]=

Compared to the naive implementation:

In[6]:=
MaxMemoryUsed[Select[Tuples[Range[10], 5], EqualTo[30]@*Total]]
Out[6]=

Possible Issues (1) 

The length of the results might be smaller than the argument m:

In[7]:=
ResourceFunction["SelectTuples"][{-1, 0, 1}, 3, EqualTo[1]@*Norm, 10]
Out[7]=

Publisher

SHuisman

Version History

  • 1.0.0 – 31 July 2019

Related Resources

License Information