views:

282

answers:

2

I want to typeset an algorithm in LaTeX. I'm using the algorithmic package and environment to do so. Everything is working great except when I add comments (using \COMMENT), they are output immediately after the statements. I would like for all the comments to be aligned (and offset from the statements). Is there an easy way to do so?

"Reproducing" the PDF output in HTML's pre, I want:

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

rather than

if condition then
   something  # comment 1
else
   something else  # comment 2
A: 
if condition then
   something        \hspace{2in} # comment 1
else
   something else   \hfill # comment 2

I'm not sure if the hspace and hfill will work inside an environment. I assume that they will. \hfill will set the comments flush right, while \hspace{space} will give you that much space between your text. good luck.

Mica
While this *will* work, it would require dinking for every case and everytime anything changes. Yuk!
dmckee
+4  A: 

I would do it like this:

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

Note 1: two document compilations are necessary to determine the maximum width of the comment.

Note 2: obviously, this only works for single line comments that aren't too long.


Following on from this idea, here's a complete example in the same sort of way, but also providing a command to have comments that break over lines:

\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}
Will Robertson
This is really superb! The different algorithmic environments in your example are unnecessary, but rather highlight that the alignment will remain across different algorithms; an added bonus.Now I need to read up on eqparbox.
foxcub
Actually that was an unintended side-effect :) If you want comments to change size between algorithms, that will be more effort (just need to change `{COMMENT}` to include a counter, really).
Will Robertson