Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting comments in LaTeX's algorithmic environment

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
like image 677
foxcub Avatar asked Nov 16 '09 19:11

foxcub


People also ask

How do you comment out an algorithm in latex?

However, in the above code, I copied that definition into \ForEach . Comments can be added using \algorithmiccomment . Formatting and placement can be modified. @alper: Add \algrenewcommand{\algorithmiccomment}[1]{\hfill// #1} to your preamble after loading algpseudocode .

Can we add comments in an algorithm?

Comments can include a description of an algorithm to make code understandable. Comments can be helpful for one's own self too if code is to be reused after a long gap.

How do you comment in an algorithm?

Use the block (/* ... */) style of comments to describe a class or function, but use the in-line (// ...) style of comments to add comments inside a class or function.

How do I add comments in Algorithm2e?

Comment. Algorithm2e provides \tcc and \tcp command to create multi-line and single line C-style comments respectively. For example, you can use \tcc to create a multi-line comment: \tcc{For odd elments in the list, we add 1, and for even elments, we add 2.


1 Answers

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}
like image 160
Will Robertson Avatar answered Nov 15 '22 10:11

Will Robertson