[Tex/LaTex] Generating random numbers without repetitions

random numbers

How do I generate in LaTeX a list of random integers, in a given range, avoiding repetitions? The command \pgfmathrandomitem selects an item from a list, but when inserted in a loop can select twice the same item. Since I am selecting questions from a list in order to prepare an exam, I cannot ask twice the same question.

Best Answer

You can remove the item from the list after selecting it, then it won't be picked again:

enter image description here

\documentclass{article}
\usepackage{tikz}

\begin{document}
\makeatletter
\pgfmathsetseed{123321}



\def\prunelist#1{%
\expandafter\edef\csname pgfmath@randomlist@#1\endcsname
        {\the\numexpr\csname pgfmath@randomlist@#1\endcsname-1\relax}
\count@\pgfmath@randomtemp 
\loop
\expandafter\let
\csname pgfmath@randomlist@#1@\the\count@\expandafter\endcsname
\csname pgfmath@randomlist@#1@\the\numexpr\count@+1\relax\endcsname
\ifnum\count@<\csname pgfmath@randomlist@#1\endcsname\relax
\advance\count@\@ne
\repeat}

\pgfmathdeclarerandomlist{mylist}{{one}{two}{three}{four}{five}{six}{seven}}

\pgfmathrandomitem\z{mylist}\z\prunelist{mylist}


\pgfmathrandomitem\z{mylist}\z\prunelist{mylist}

\pgfmathrandomitem\z{mylist}\z\prunelist{mylist}

\pgfmathrandomitem\z{mylist}\z\prunelist{mylist}

\pgfmathrandomitem\z{mylist}\z\prunelist{mylist}

\pgfmathrandomitem\z{mylist}\z\prunelist{mylist}

\pgfmathrandomitem\z{mylist}\z\prunelist{mylist}



\end{document}

to declare an integer list:

\def\declarenumlist#1#2#3{%
\expandafter\edef\csname pgfmath@randomlist@#1\endcsname{#3}%
\count@\@ne
\loop
\expandafter\edef
\csname pgfmath@randomlist@#1@\the\count@\endcsname
  {\the\count@}
\ifnum\count@<#3\relax
\advance\count@\@ne
\repeat}

%\pgfmathdeclarerandomlist{mylist}{{one}{two}{three}{four}{five}{six}{seven}}


\declarenumlist{mylist}{1}{10}% list from 1 to 10 inclusive.