# How would I return a random Mathematica command?

I'm doing some metaprogramming. How would I make a Mathematica function that returns a random Mathematica command? Is there a list of command names that I could use RandomChoice on?

I'm looking for something better than selecting random letters until getting Protected in the Attributes, which is all I've been able to think of so far.

## 3 Answers

There are a lot of commands! One way to get a list is to use Names["*"], which will return all the symbols Mathematica knows. Since commands start with capital letters, you can gain more control over the list by asking for only a subset. For example,

all = {"A*", "B*", "C*"};
Names[#] & /@ all


provides a list of all commands that start with A, B, or C. You could customize the all to suit your preferences.

• Nowadays, one can use WolframLanguageData["RandomEntities"]. – J. M. is away Jun 7 '16 at 10:01

Get the full list of Mathematica functions here:

myFunctionList = Import["http://reference.wolfram.com/language/guide/\
AlphabeticalListing.html"];


Strip the list of header and footer material, and select a random element:

RandomChoice[StringSplit[StringTake[myFunctionList, {3245, -1225}]]]


Or, based on the approach of bill s:

RandomChoice@Flatten[Names[#] & /@ (StringJoin[#, "*"] & /@ CharacterRange["A", "Z"])]


Here's a piece of code that lets you see random Wolfram Language code snippets, rather than just command names.

RandomExample[] := Module[{dir, file, inputs, output, cap, i = 0, j = 1, in},
dir = DirectoryName[FindFile["ExamplePages/CreateMolecularGraphs.nb"]];
file = RandomChoice[FileNames["*", dir]];
output = Import[file, {"Cells", "Output"}][];

cap = CellLabel /. Options[output];
If[!StringQ[cap], Return[\$Failed]];
cap = ToExpression[StringReplace[cap, "Out[" ~~ x__ ~~ "]" ~~ __ :> x]];

inputs = Import[file, {"Cells", "Input"}];

CellPrint[TextCell[
StringReplace[file, __ ~~ "ExamplePages" :> "ExamplePages"],
"Subsubsection"
]];

CellPrint[Reap[
While[i < cap && j <= Length[inputs],
in = CellLabel /. Options[inputs[[j]]];
If[StringQ[in],
i = ToExpression[StringReplace[in, "In[" ~~ x__ ~~ "]" ~~ __ :> x]]
];
Sow[inputs[[j++]]]
]
][[-1, 1]]];

CellPrint[output];
]  