1

I want to run the steps of a loop in random order and also save the order in which the iterations were carried out:

\documentclass[english]{article}
\usepackage{tikz}
\newcommand\NonRandomizedIndexList{3,4,5,6,7}
\newcommand\PermutedIndexList{3,5,6,4,7}
%
\begin{document}
\foreach \x in \PermutedIndexList {
Run a complicated code that involves \x .\\
        }\\
Remember that the order in which the loop was run was: \PermutedIndexList.
\end{document}

My question is how can I generate in LaTex the Macro PermutedIndexList from the original set NonRandomizedIndexList. In Matlab, function `randperm()' would do the job, but I am looking for solution within LaTeX.

Sebastian
  • 109

1 Answers1

2

Something like this? Requires lualatex:

\documentclass[varwidth,border=5]{standalone}
\usepackage{pgffor}
\def\randomiselist#1#2{\edef#2{\directlua{%
local i, j, k, n, s, t, v
t = {#1}
n = 0
for i, v in ipairs(t) do
  n = n + 1
end
for i = 1,n do
  j = math.random(i,n)
  k = t[i]
  t[i] = t[j]
  t[j] = k
end
s = ''
for i = 1,n do
  s = s .. t[i]
  if i < n then s = s .. ',' end
end
tex.print(s)
}}}
\begin{document}
\def\lista{3,4,5,6,7,8}
\randomiselist\lista\listb
\tt lista -> \meaning\lista \par
\tt listb -> \meaning\listb \par
\foreach \i [count=\j] in \listb { listb[\j]=\i \par }
\end{document}

enter image description here

And to produce a list of (pseudo-) random uniform zeros and ones:

\documentclass[varwidth,border=5]{standalone}
\usepackage{pgffor}
\def\booleanrandomlist#1#2{\edef#2{\directlua{%
local i, s, v
s = ''
for i, v in ipairs({#1}) do
  s = s .. math.random(0,1) .. ','
end 
tex.print(s:sub(1, s:len()-1))
}}}
\begin{document}
\def\lista{3,4,5,6,7,8} 
\booleanrandomlist\lista\listb
\tt lista -> \meaning\lista \par
\tt listb -> \meaning\listb \par
\foreach \i [count=\j] in \listb { listb[\j]=\i \par }
\end{document}

enter image description here

Mark Wibrow
  • 70,437