Generate random color in way that works with both pdflatex and lualatex

The luatex85 package does

\let\pdfuniformdeviate\uniformdeviate

You can thus do \usepackage{luatex85} or

\documentclass{article}
\usepackage{xcolor}

\unless\ifdefined\pdfuniformdeviate
  \let\pdfuniformdeviate\uniformdeviate
\fi

\definecolor{randomcolor}{RGB}
{
    \pdfuniformdeviate 255,
    \pdfuniformdeviate 255,
    \pdfuniformdeviate 255
}
\extractcolorspec{randomcolor}\test
\typeout{\test}

\stop

This will type out something like

{rgb}{0.84706,0.4,0.68234}

with both pdflatex or lualatex. I guess that, when random numbers will be available also in xelatex, a common interface will be added to the LaTeX kernel.


There is also the lcg package (short for Linear Congruential Generator), that works with all compilers, including lualatex. The package provides a command \rand to generate a random number and store it in the rand counter. For use in \definecolor you should convert the counter with \the\value.

You can set the bounds of the random generator with the package options first and last, and optionally change them within the document using the \reinitrand command. The default seed is based on the system clock, using the minutes as unit (so the output will change only once per minute). You can also provide a custom seed.

MWE:

\documentclass{article}
\usepackage[first=1,last=255]{lcg}
\usepackage{xcolor}
\rand\edef\colora{\the\value{rand}}
\rand\edef\colorb{\the\value{rand}}
\rand\edef\colorc{\the\value{rand}}

\definecolor{randomcolor}{RGB}
{
    \colora,
    \colorb,
    \colorc
}
\begin{document}
\colorbox{randomcolor}{Random color: \colora,\colorb,\colorc}
\end{document}

Result:

enter image description here


Based on Randomly assign background colour for each frame

Another approach based on pgf:

\documentclass{article}

\usepackage{pgf}
\usepackage{pgffor}
\usepackage{xcolor}

\usepackage{ifluatex}
\usepackage{ifxetex}

\ifluatex
  \let\pdfrandomseed\randomseed
\fi

\ifxetex
  \pgfmathsetseed{\time}
\else
  \pgfmathsetseed{\number\pdfrandomseed}
\fi

\newcommand{\randomcolor}{%
    \pgfmathsetmacro{\R}{rnd}%
    \pgfmathsetmacro{\G}{rnd}%
    \pgfmathsetmacro{\B}{rnd}%
    \definecolor{randomcol}{rgb}{\R,\G,\B}%
}

\begin{document}

\noindent%
\foreach \n in {1,...,1350}{%
   \randomcolor\color{randomcol}\rule{0.41cm}{0.41cm}\-%
}

\end{document}

enter image description here