Formatting Comments in LaTeX Algorithmic Environment

I want to type an algorithm in LaTeX. I use an algorithmic package and environment for this. Everything works fine, except when I add comments (using \ COMMENT), they are displayed immediately after the statements. I would like all comments to be aligned (and biased from statements). Is there an easy way to do this?

"Replaying" PDF output in HTML pre, I want:

if condition then
   something         # comment 1
else
   something else    # comment 2

but not

if condition then
   something  # comment 1
else
   something else  # comment 2
+5
source share
3 answers

I would do it like this:

\ usepackage {eqparbox}
\ renewcommand {\ algorithmiccomment} [1] {\ hfill \ eqparbox {COMMENT} {\ # # 1}}

1: .

2: , , .


, , , :

\documentclass{amsbook}
\usepackage{algorithmic,eqparbox,array}
\renewcommand\algorithmiccomment[1]{%
  \hfill\#\ \eqparbox{COMMENT}{#1}%
}
\newcommand\LONGCOMMENT[1]{%
  \hfill\#\ \begin{minipage}[t]{\eqboxwidth{COMMENT}}#1\strut\end{minipage}%
}
\begin{document}
\begin{algorithmic} 
\STATE do nothing \COMMENT{huh?} 
\end{algorithmic}
\begin{algorithmic} 
\STATE do something \LONGCOMMENT{this is a comment broken over lines} 
\end{algorithmic}
\begin{algorithmic} 
\STATE do something else \COMMENT{this is another comment} 
\end{algorithmic}
\end{document}
+11
if condition then
   something        \hspace{2in} # comment 1
else
   something else   \hfill # comment 2

, hspace hfill . , . \ hfill , \hspace {space} . .

0

If you need your own indentation for different algorithms, you can do this by including a counter in the redefinition of comment commands. Here is an example:

\documentclass{amsbook}
\usepackage{algorithmicx,algorithm,eqparbox,array}

\algrenewcommand{\algorithmiccomment}[1]{\hfill// \eqparbox{COMMENT\thealgorithm}{#1}}
\algnewcommand{\LongComment}[1]{\hfill// \begin{minipage}[t]{\eqboxwidth{COMMENT\thealgorithm}}#1\strut\end{minipage}}

\begin{document}
\begin{algorithm}
\begin{algorithmic}
\State{do nothing}\Comment{huh?}
\end{algorithmic}
\caption{Test Alg}
\end{algorithm}

\begin{algorithm}
\begin{algorithmic}
\State{do something} \LongComment{this is a comment broken over lines}
\State{do something else} \Comment{this is another comment}
\end{algorithmic}
\caption{Other Alg}
\end{algorithm}
\end{document}
0
source

All Articles