Context
I'm trying to get an automatic exam where I can generate random numbers (using pgfmathrandominteger) in the AMC package to create different questions using code (listings) and inputing these random numbers to the code. For example, change the value a variable will get, or change the number of iterations on a loop, etc.
Problem
However, the listing package is not easy to work with in the AMC environment (see How to expand a macro to use it inside a question in AMC?). Moreover, to add the random number that should appear on the code, and to be generated that number from the question is becoming a challenge.
For example, in the code below, I can generate the number ( \pgfmathrandominteger{\mynum}{1}{8}) but when using more questions it doesn't work (same happens when using more than one copy).
Ideally, I should generate the random number inside the question, so every time the question is parsed by AMC a new number is generated and then it should be parsed by the box. However, the box is already typeset when declared (as far as I understand). Thus, when I use it on the lstlisting code (if I could reach the \mynum macro) I still need to be able to reform that environment again and again.
How that behavior can be achieved?
\documentclass{article}
\usepackage[box]{automultiplechoice}
\usepackage{listings}
\usepackage{tikz}
\lstset{ escapeinside={@}{@}}
% a simple wrapper to create boxes automatically
\makeatletter
\newcounter{myboxcounter}
\newenvironment{mybox}{%
\stepcounter{myboxcounter}%
\expandafter\newsavebox\csname foobox\roman{myboxcounter}\endcsname
\global\expandafter\setbox\csname foobox\roman{myboxcounter}\endcsname\hbox\bgroup\color@setgroup\ignorespaces
}{%
\color@endgroup\egroup
}
\newcommand{\insertbox}{\stepcounter{myboxcounter}%
\edef\name{foobox\roman{myboxcounter}}\edef\x{%
\expandafter\usebox\csname\name\endcsname}\x}
\makeatother
\begin{document}
%%% preparation of the groups
\pgfmathrandominteger{\mynum}{1}{8}
\begin{mybox}
\begin{lstlisting}[language=C++]
int a = @\mynum@;
a = a + 10;
\end{lstlisting}
\end{mybox}
\element{code}{
\begin{question}{code 1}
Which is the result of \texttt{a} \mynum?
\insertbox
\begin{choices}
\correctchoice{\pgfmathparse{\mynum+10}\pgfmathresult}
\wrongchoice{20}
\wrongchoice{0}
\wrongchoice{30}
\end{choices}
\end{question}
}
%%% copies
\setcounter{myboxcounter}{0}
\onecopy{1}{% when changed the number of copies to more than one it won't work
\insertgroup{code}
}
\end{document}



\onecopy{2}to1). That is one of the problems that the macro part won't work on multiple copies (by several questions or copies). – adn Mar 30 '15 at 01:21