# How to Create Random Letter?

I am trying to create algebra quizzes which are generated by random numbers and each exercise's variable is a random letter from the alphabet.

I think I can do the random numbers.

Not sure how to do the random letters. Is there a function for this in pgf? Or do I have to use \pgfmathdeclarerandomlist{\listname}{<EntireAlphabet>} and \pgfmathrandomitem?

Because we are dealing with TeX, who cares about efficiency

\documentclass[]{article}
\usepackage{pgffor,pgfmath}
\def\getrandomletter{%
\pgfmathrandominteger{\mytemp}{1}{26}%
\foreach\x[count=\xi] in{a,...,z}{\ifnum\xi=\mytemp\x\breakforeach\fi}%
}
\begin{document}
\foreach\x in{1,...,26}{\getrandomletter}
\end{document}


I was being silly not remembering alphalph package. It converts numbers into various symbols.

\documentclass[]{article}
\usepackage{pgffor,pgfmath,alphalph}
\def\getrandomletter{\pgfmathrandominteger{\mytemp}{1}{26}\alphalph{\mytemp}}
\begin{document}
\foreach\x in{1,...,26}{\getrandomletter}
\end{document}


gives the same output.

OK I keep on being silly. pgffor already understands letters to convert numbers to letters. So we don't need alphalph. I'll drink more coffee.

\documentclass[]{article}
\usepackage{pgffor,pgfmath}
\def\getrandomletter{\pgfmathrandominteger{\zzz}{1}{26}\csname pgffor@alpha\endcsname{\zzz}}
\begin{document}
\foreach\x in{1,...,26}{\getrandomletter}
\end{document}

• What does [count=\xi] do? Jul 23 '17 at 0:00
• @WeCanLearnAnything holds the number of spins of the loop Jul 23 '17 at 0:06
• And there is \@alph from the LaTeX kernel. Jul 23 '17 at 12:34
• @HeikoOberdiek Apparently coffee isn't working for me :D facepalm... Jul 23 '17 at 12:35
• Or \foreach\i in{1,...,9}{\pgfmathrandominteger{\zzz}{65}{90}\char\zzz\relax}. Jul 23 '17 at 12:57

Using only plain TeX macros, you can do this:

\input random
\newcount\code
\def\ranx{\setrannum\code{a}{z}\char\code}

\ranx \ranx \ranx \ranx \ranx \ranx \ranx \ranx \ranx

\bye

• Wow, that seems very simple. What does \code{'a}{'z}\char\code do? I imagine the {'a}{'z} makes the alphabet the set of objects \ranx can be assigned to, but I don't know what the other parts are for. Jul 24 '17 at 19:59

The following doesn't (at the moment) work with XeLaTeX:

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewExpandableDocumentCommand{\randomletter}{}
{
\int_to_alph:n { \fp_eval:n { randint(1,26) } }
}
\NewExpandableDocumentCommand{\randomLetter}{}
{
\int_to_Alph:n { \fp_eval:n { randint(1,26) } }
}
\ExplSyntaxOff

\begin{document}

\randomletter\ \randomletter\ \randomletter\ \randomletter\ \randomletter

\randomLetter\ \randomLetter\ \randomLetter\ \randomLetter\ \randomLetter

\end{document}