Wolfram Research

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

Find out for which 2-tuple the sum is a prime:

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

Only get the first five:

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

Scope

Find the first 15 three-letter palindromic lists:

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

Applications

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

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 naive implementation:

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

Possible Issues

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]=

Resource History

License Information