在此伪代码摘录中,是否可以为变量添加新参数五使用类似语法\ForAll {$v$}{$v \in V(G)$}
来获取输出下一个视频?
\documentclass{article}
\usepackage{algpseudocode}
\usepackage{algorithm}
\renewcommand\algorithmicforall{\textbf{repeat for each}}
\def\algorithmicnext{\textbf{next}}%
\algdef{SE}[FOR]{ForAll}{EndFor}[1]
{\algorithmicforall\ #1}
{\algorithmicnext}
\begin{document}
\begin{algorithm}
\caption{The Bellman-Kalaba algorithm}
\begin{algorithmic}[1]
\ForAll {$v \in V(G)$}
\State $l(v) \leftarrow \infty$
\EndFor
\end{algorithmic}
\end{algorithm}
\end{document}
我只想使用这些包algpseudocode
,algorithm
因为这是一个遗留代码项目。
答案1
和
\newcommand \algorithmicnext[1]{\textbf{next #1}}
代码
\documentclass{article}
\usepackage{algpseudocode}
\usepackage{algorithm}
\renewcommand\algorithmicforall{\textbf{repeat for each}}
\newcommand \algorithmicnext[1]{\textbf{next #1}}%<- this line
%\def\algorithmicnext{\textbf{next}}%
\algdef{SE}[FOR]{ForAll}{EndFor}[1]
{\algorithmicforall\ #1}
{\algorithmicnext}
\begin{document}
\begin{algorithm}
\caption{The Bellman-Kalaba algorithm}
\begin{algorithmic}[1]
\ForAll {$v \in V(G)$}
\State $l(v) \leftarrow \infty$
\EndFor{v}
\end{algorithmic}
\end{algorithm}
\end{document}
答案2
我会为这种循环定义一个适当的结构:
\documentclass{article}
\usepackage{algpseudocode}
\usepackage{algorithm}
\algnewcommand\algorithmicrepeatforeach{\textbf{repeat for each}}
\algnewcommand{\algorithmicendrepeatforeach}[1]{\textbf{next} #1}
\algdef{SE}[FOR]{RepeatForEach}{EndRepeatForEach}[1]
{\algorithmicrepeatforeach\ #1}
{\algorithmicendrepeatforeach}
\begin{document}
\begin{algorithm}
\caption{The Bellman-Kalaba algorithm}
\begin{algorithmic}[1]
\RepeatForEach {$v \in V(G)$}
\State $l(v) \leftarrow \infty$
\EndRepeatForEach{$v$}
\end{algorithmic}
\end{algorithm}
\end{document}
这借鉴了pascal974 的回答(已获好评),但有变化。
使用不同的语法:在 中使用两个参数\RepeatForEach
,第一个是要压入堆栈的变量;\EneRepeatForEach
将弹出并使用它。这允许嵌套循环,而不必在末尾处理变量。
\documentclass{article}
\usepackage{algpseudocode}
\usepackage{algorithm}
\algnewcommand\algorithmicrepeatforeach{\textbf{repeat for each}}
\algnewcommand{\algorithmicendrepeatforeach}{\textbf{next}}
\algdef{SE}[FOR]{RepeatForEach}{EndRepeatForEach}[2]
{\pushvar{#1}\algorithmicrepeatforeach\ #2}
{\algorithmicendrepeatforeach\ \popvar}
\ExplSyntaxOn
\seq_new:N \g_alg_varstack_seq
\NewDocumentCommand{\pushvar}{m}
{
\seq_gpush:Nn \g_alg_varstack_seq { #1 }
}
\NewDocumentCommand{\popvar}{}
{
\seq_gpop:NN \g_alg_varstack_seq \l_tmpa_tl
\tl_use:N \l_tmpa_tl
}
\ExplSyntaxOff
\begin{document}
\begin{algorithm}
\caption{The Bellman-Kalaba algorithm}
\begin{algorithmic}[1]
\RepeatForEach {$v$}{$v \in V(G)$}
\State $l(v) \leftarrow \infty$
\RepeatForEach {$u$}{$u\in X$}
\State whatever
\EndRepeatForEach
\EndRepeatForEach
\end{algorithmic}
\end{algorithm}
\end{document}