Algorithm2e 注释行对齐问题

Algorithm2e 注释行对齐问题

我想在 algorithm2e 的算法环境中对齐注释,以便多行注释的每一行都左对齐。

请参阅以下 MWE。在此 MWE 中,注释的第二行和第三行与算法的伪代码左对齐。我想将它们与注释的第一行对齐,因此单词“in”和“algorithm”应与第一行的单词“One”对齐。

\documentclass{article}
\usepackage{algorithm2e}
\begin{document}
\begin{algorithm}[tbp]
\LinesNumbered
\caption{Text}
\label{alg:Algo}

\BlankLine

$a \gets (a+1)^a$\tcp*{One long comment line which should be aligned in such a way that the comment shouldn't go into the algorithm}

\Return{Result}\;
\end{algorithm}
\end{document}

编辑: 针对 Steven B. Segletes 的回答进行的编辑。如果注释行嵌套在循环中,则对齐会出现问题。此外,由于 parbox,还会发出水平框未满的警告。

梅威瑟:

\documentclass{article}
\usepackage{algorithm2e}
\newlength\algowd
\def\savewd#1{\setbox0=\hbox{#1\hspace{.7in}}\algowd=\wd0\relax#1}
\newcommand\algolines[2]{\savewd{#1}%
  \tcp*{\parbox[t]{\dimexpr\algowidth-\algowd}{#2}}}
\begin{document}

\begin{algorithm}[tbp]
\LinesNumbered
\caption{Text}
\label{alg:Algo}

\BlankLine

\ForEach{$a \in A$}{
   \algolines{$a \gets (a+1)^a$}{One long comment line which should be aligned in such a way that the comment shouldn't go into the algorithm}
 }

\Return{Result}\;
\end{algorithm}

\end{document}

答案1

我在这里重新列出了原来的非自动化方法,因为自动化方法(见下文)显示出了缺陷。使用手动方法,注释被放置在 中\parbox,但用户必须指定它的宽度。OP 提到的未满框可以通过明确注释 来补救\raggedright

\documentclass{article}
\usepackage{algorithm2e}
\begin{document}
\begin{algorithm}[tbp]
\LinesNumbered
\caption{Text}
\label{alg:Algo}

\BlankLine

$a \gets (a+1)^a$\tcp*{\parbox[t]{3.3in}{\raggedright One long comment line which should 
be aligned in such a way that the comment shouldn't go into the algorithm}}

\Return{Result}\;
\end{algorithm}
\end{document}

-----当嵌套循环时,自动化方法会失败

您可以在\parbox.EDITED 中执行此操作以自动计算 的宽度\parbox。在这里,我介绍\algolines{}{}以参数\tcp作为其第一个参数并以多行注释作为其第二个参数的方法。

\documentclass{article}
\usepackage{algorithm2e}
\newlength\algowd
\def\savewd#1{\setbox0=\hbox{#1\hspace{.7in}}\algowd=\wd0\relax#1}
\newcommand\algolines[2]{\savewd{#1}%
  \tcp*{\parbox[t]{\dimexpr\algowidth-\algowd}{#2}}}
\begin{document}

\begin{algorithm}[tbp]
\LinesNumbered
\caption{Text}
\label{alg:Algo}

\BlankLine

\algolines{$a \gets (a+1)^a$}{One long comment line which should be aligned in such a way that the comment shouldn't go into the algorithm}

\Return{Result}\;
\end{algorithm}

\begin{algorithm}[tbp]
\LinesNumbered
\caption{Text}
\label{alg:Algo}

\BlankLine

\algolines{$a \gets (a+1)^a (b+1)^b$}{One long comment line which should be aligned in such a way that the comment shouldn't go into the algorithm}

\Return{Result}\;
\end{algorithm}
\end{document}

在此处输入图片描述

相关内容