使用 \usepackage[noend]{algpseudocode} 进行 ForEach 循环

使用 \usepackage[noend]{algpseudocode} 进行 ForEach 循环

我用了这里的完美答案如何在现有的ForAll循环的基础上定义一个ForEach循环? 定义for each循环。

一旦我用 替换\usepackage{algpseudocode}\usepackage[noend]{algpseudocode}我仍然会看到end for

我该如何修改代码以使其能够正常工作\usepackage[noend]{algpseudocode}

我的代码:

\documentclass{llncs}

\usepackage{graphicx}

\usepackage{tikz}
\usetikzlibrary{patterns, arrows,matrix, positioning, decorations.markings, calc, arrows.meta}

\usepackage{algcompatible}

\usepackage{environ}
\usepackage{textcomp}

\usepackage[hyphens]{url}
\usepackage[hidelinks]{hyperref}
\hypersetup{breaklinks=true}
\urlstyle{same}
\usepackage{csquotes}

\usepackage{siunitx}
\usepackage{gensymb}

\usepackage{cleveref}
\usepackage{listings}

\usepackage{algorithm}% http://ctan.org/pkg/algorithms
\usepackage[noend]{algpseudocode}% http://ctan.org/pkg/algorithmicx

\algnewcommand\algorithmicinput{\textbf{Input:}}
\algnewcommand\INPUT{\item[\algorithmicinput]}

\algnewcommand\algorithmicoutput{\textbf{Output:}}
\algnewcommand\OUTPUT{\item[\algorithmicoutput]}

\algnewcommand\algorithmicassume{\textbf{Assume:}}
\algnewcommand\ASSUME{\item[\algorithmicassume]}

\renewcommand{\COMMENT}[2][.4]{%
  \leavevmode\hfill\makebox[#1\linewidth][l]{$\triangleright$~#2}}

\let\emptyset\varnothing

\algblockdefx[Foreach]{Foreach}{EndForeach}[1]{\textbf{for each} #1 \textbf{do}}{\textbf{end for}}

% avoid breaking "N-d" on separate lines
\usepackage[shortcuts]{extdash}

\newcommand{\Nd}{}% To make sure that it isn't already defined 
\def\Nd/{$N$\=/d array}

\makeatletter
\def\HiLi{\hskip-\ALG@thistlm\leavevmode\rlap{\hbox to \linewidth{\color{gray!15}\leaders\hrule height .8\baselineskip depth .8ex\hfill}}\hskip+\ALG@thistlm}
\makeatother

\makeatletter
\newcommand{\algcolor}[2]{%
    \hskip-\ALG@thistlm\colorbox{#1}{\parbox{\dimexpr\linewidth-2\fboxsep}{\hskip\ALG@thistlm\relax #2}}%
}
\newcommand{\algemph}[1]{\algcolor{gray}{#1}}
\makeatother

% similar to binary operator $\bmod$
\makeatletter
\newcommand*{\bdiv}{%
  \nonscript\mskip-\medmuskip\mkern5mu%
  \mathbin{\operator@font div}\penalty900\mkern5mu%
  \nonscript\mskip-\medmuskip
}
\makeatother


\usepackage{epsfig}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{mathtools}

\usepackage{epstopdf}
\usepackage[labelsep=period]{caption}

\begin{document}


\section{G}

\begin{algorithm}[t]
  \caption{G}
  \label{alg:ge}

  \begin{algorithmic}[1]
    \Procedure{R}{$P, s_i, \varepsilon_i$}
        \Foreach{$p \in P$}
            \textproc{Cut-One}($p, s_i, \varepsilon_i$)
        \EndForeach
    \EndProcedure
  \end{algorithmic}
\end{algorithm}

\end{document}

答案1

Foreach您可以使用以下方式定义新的块语句

\algblockdefx[Foreach]{Foreach}{EndForeach}[1]{\textbf{for each} #1 \textbf{do}}{\textbf{end for}}

与您链接到的另一篇文章中的提议相反,您不会重复使用\endfor(受noend选项影响),而是引入一个新的关闭命令\EndForeach,不受选项影响noend。为了使其敏感,请在上面一行下面添加以下几行:

\makeatletter
\ifthenelse{\equal{\ALG@noend}{t}}{\algtext*{EndForeach}}{}
\makeatother

相关内容