4

I have a list and then two randomly selected items from them.

But those two items are always the same. Why?

\documentclass{article}

\usepackage{pgf}
\usepackage{pgffor}
 \pgfmathsetseed{\number\pdfrandomseed}

\newcommand{\InitVariables}
{%
\pgfmathdeclarerandomlist{List}{{2}{3}{4}{5}{6}{7}{8}{9}}
\pgfmathrandomitem{\VarA}{List}
\pgfmathrandomitem{\VarB}{List}
}



\begin{document}


ATTEMPT ONE
\InitVariables

Variable A is \VarA .

Variable B is \VarB .


ATTEMPT TWO
\InitVariables

Variable A is \VarA .

Variable B is \VarB .

ATTEMPT THREE
\InitVariables

Variable A is \VarA .

Variable B is \VarB .

\end{document}

enter image description here

1 Answers1

4

\pgfmathrandomitem doesn't actually define \varA to be a randomly selected item, it defines it to choose such an item, and then \VarB gets the same definition, both are defined to be

> \VarB=macro:
->\csname pgfmath@randomlist@List@\pgfmath@randomtemp \endcsname .

as shown by the \show.

Here as the items are unexpandable you cansimply edef expand the definitions to get the actual values into the macros, as shown by the 2nd and 4th \show.

> \VarA=macro:
->5.

example document:

\documentclass{article}

\usepackage{pgf}
\usepackage{pgffor}
 \pgfmathsetseed{\number\pdfrandomseed}

\newcommand{\InitVariables}
{%
\pgfmathdeclarerandomlist{List}{{2}{3}{4}{5}{6}{7}{8}{9}}
\pgfmathrandomitem{\VarA}{List}
\show\VarA
\edef\VarA{\VarA}
\show\VarA
\pgfmathrandomitem{\VarB}{List}
\show\VarB
\edef\VarB{\VarB}
\show\VarB
}



\begin{document}


ATTEMPT ONE
\InitVariables

Variable A is \VarA .

Variable B is \VarB .


ATTEMPT TWO
\InitVariables

Variable A is \VarA .

Variable B is \VarB .

ATTEMPT THREE
\InitVariables

Variable A is \VarA .

Variable B is \VarB .

\end{document}
David Carlisle
  • 757,742
  • But why, in that case, does it always choose the same item randomly twice? If \VarA is 'choose a random item' rather than some random item and \VarB is 'choose a random item' rather than some random item, then \VarA \VarB is 'choose a random item choose a random item'. So it should choose a random item twice and they shouldn't always be the same. – cfr Sep 26 '17 at 01:37
  • 1
    @cfr it picks a random number in \pgfmath@randomtemp then defines varA to choose the \pgfmath@randomtemp'th item, then it puts another random number into \pgfmath@randomtemp again and defines varB to chooose the \pgfmath@randomtemp 'th item so varA and varB both get defined to choose the \pgfmath@randomtemp 'th ite and \pgfmath@randomtemp is the second random number calculated – David Carlisle Sep 26 '17 at 06:58