Function Repository Resource:

RandomPartChoice

Source Notebook

Choose random parts of an expression

Contributed by: Richard Hennigan (Wolfram Research)

ResourceFunction["RandomPartChoice"][expr]

chooses a random subexpression from expr.

ResourceFunction["RandomPartChoice"][expr,count]

chooses count subexpressions.

ResourceFunction["RandomPartChoice"][expr,count,levelspec]

only considers subexpressions at levels given by levelspec.

ResourceFunction["RandomPartChoice"][expr,count,levelspec,wrapper]

applies wrapper to each item before returning the result.

ResourceFunction["RandomPartChoice"][expr,count,levelspec,wrapper,pattern]

only considers subexpressions that match pattern.

Details and Options

ResourceFunction["RandomPartChoice"][expr] chooses with equal probability between all of the subexpressions of expr.
ResourceFunction["RandomPartChoice"] gives a different sequence of pseudorandom choices whenever you run the Wolfram Language. You can start with a particular seed using SeedRandom.
A Method option to SeedRandom can be given to specify the pseudorandom generator used.
ResourceFunction["RandomPartChoice"][expr,count,levelspec,wrapper,pattern] tests all the subparts of expr in turn to try and find ones that match pattern.
ResourceFunction["RandomPartChoice"] looks only for matches to values in Association objects that appear in expr.
The default level specification for ResourceFunction["RandomPartChoice"] is {0,Infinity}, with HeadsFalse.
ResourceFunction["RandomPartChoice"] uses standard level specifications:
nlevels 1 through n
Infinitylevels 1 through Infinity
{n} level n only
{n1,n2} levels n1 through n2
A positive level n consists of all parts of expr specified by n indices.
A negative level -n consists of all parts of expr with depth n.
Level 0 corresponds to the whole expression.

Examples

Basic Examples (5) 

Get a random part of an expression:

In[1]:=
ResourceFunction[
 "RandomPartChoice"][{1 + x^2, 5, x^4, a + (1 + x^2)^2}]
Out[1]=

Get multiple parts:

In[2]:=
ResourceFunction["RandomPartChoice"][{f[x], g[a, b], h[c, d]}, 10]
Out[2]=

Provide a level specification:

In[3]:=
ResourceFunction["RandomPartChoice"][{f[x], g[a, b], h[c, d]}, 5, 1]
Out[3]=

Apply a function to each item before returning:

In[4]:=
ResourceFunction["RandomPartChoice"][
 Hold[1 + 1, 2 + 2, 3 + 3], 3, 1, HoldForm]
Out[4]=

Restrict sampling to elements that match a given pattern:

In[5]:=
ResourceFunction["RandomPartChoice"][
 Hold[1 + 1, 2 + 2, 3 + 3], Automatic, Automatic, HoldForm, _Plus]
Out[5]=

Scope (2) 

Use Automatic for the count to obtain the one-argument behavior when providing additional arguments:

In[6]:=
ResourceFunction[
 "RandomPartChoice"][{f[x], g[a, b], h[c, d]}, Automatic, 1]
Out[6]=