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
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 .
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.
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.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With