[Tex/LaTex] How to convert number to length

lengthsrandom numbers

I'm trying to generate a "word cloud" by using \mboxes with random spaces around words.

In the code below I've removed stuff that change the font size, and I've replaced \mboxes by \frameboxes for debug purpose.

\documentclass{article}

\usepackage[first=1, last=10]{lcg}

\newcommand*{\wordtag}[1]{%
    \framebox{\vspace{3pt}\hspace{5pt}#1\vspace{1pt}\hspace{6pt}}%
}


\begin{document}
\rand


\wordtag{color}
\wordtag{animals}


\end{document}

When I replace length with \rand (i.e. \vspace{\rand pt}), I get the following error:

! Illegal unit of measure (pt inserted).

Does anyone know how to fix this error?

And why the \rand at the beginning of the document doesn't print anything?

Is there a better way to produce a word cloud?

Best Answer

The manual of the lcg package states:

\rand
Each call of the command \rand will write a new random number to the counter provided by the user with the key [=package option] counter or to the standard counter of this package rand. Now it's possible to do whatever can be done with counters.

So \rand is not expanding to a number and therefore doesn't typeset anything and can't be used in a length. You need to use it first and then can use the rand counter using \value{rand}, e.g. \vspace{\value{rand} pt}.

You could also use the math engine of the pgf package. It provides \pgfmathrandom{x,y} (also accessible using \pgfmathparse{random(x,y)} and friends) and stores the result into \pgfmathresult. Here x and y are the same numbers as first and last with lcg.

\usepackage{pgf}
% ...
\pgfmathrandom{1,10}
\vspace{\pgfmathresult pt}

% or even
\newlength{\randomlength}
\pgfmathsetlength{\randomlength}{random(1,10)}
\vspace{\randomlength}
Related Question