[Tex/LaTex] How to include random images

graphicsrandom numbers

I'd like to make LaTeX pick one image file randomly from a series of eight images, and include it. I found that ''lcg'' package can generate random numbers:

\usepackage{lcg}
\reinitrand[counter=sec,first=1,last=8]

So i expected this line to include one of the images randomly:

\includegraphics[width=0.6cm]{excl0\rand\arabic{sec}c.png}

Where the file names are excl01c.png, excl02c.png, and so on.
The result was not like i have imagined, i got an error message:

Runaway definition?
->excl0\cr@nd = 126\advance \cr@nd \inputlineno \multiply \cr@nd 3\advance \ETC
.
! TeX capacity exceeded, sorry [main memory size=3000000].
<argument> Random number generator initiali
                                       zed to \the \cr@nd

My question is what is the reason of this kind of error, and how to fix it, how to make LaTeX choose an image file randomly?

Best Answer

The \rand instruction computes a random number and stores it in the sec counter. On the other hand, the argument to \includegraphics should be a file name (after macro expansion), not the set of instructions to compute it.

Just perform the computation before doing \includegraphics:

\rand\includegraphics[width=0.6cm]{excl0\arabic{sec}c.png}

Note

\rand will do some computations which are not allowed in an "expansion only" context. The string passed as argument to \includegraphics (or \input, that uses the same mechanism) can contain macros, but these should be able to expand to characters only.

Extensions

If you need to use files numbered from 01 to 20, say, you have to ensure that the command prints a padding zero for numbers less than 10; the LaTeX kernel provides \two@digits for this:

\makeatletter
\newcommand{\printrandom}{\two@digits{\thesec}}
\makeatother

\rand\includegraphics[width=0.6cm]{excl\printrandom c.png}

For more digits, you can emulate the behavior of \two@digits:

  1. Two digits

    \newcommand{\printrandom}{\ifnum\value{sec}<10 0\fi\arabic{sec}}
    
  2. Three digits

    \newcommand{\printrandom}{\ifnum\value{sec}<100 0\fi\ifnum\value{sec}<10 0\fi\arabic{sec}}
    

Use again \rand\includegraphics[width=0.6cm]{excl\printrandom c.png}

Related Question