我想以随机顺序运行循环的步骤并保存执行迭代的顺序:
\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}
我的问题是,如何在 LaTex 中PermutedIndexList
从原始 集生成宏NonRandomizedIndexList
。在 Matlab 中,函数“randperm()”可以完成这项工作,但我在 LaTeX 中寻找解决方案。
答案1
像这样吗?要求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}
并生成一个(伪)随机均匀零和一的列表:
\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}