2

I'm trying to add comments on their own line. the default behaviour of \Comment{} is to place the comment on the same line as a \State. My current hack is to just do

\documentclass{article}
\usepackage{amsmath}
\usepackage{caption}
\usepackage{algpseudocode}
\usepackage{algorithm}
\captionsetup\[algorithm\]{labelformat=empty}
\begin{document}
\begin{algorithm}
\caption{Init}
\begin{algorithmic}\[1\]
  \State // Here is a comment the way I want it.
  \State $x \gets y$
  \end{algorithmic}
\end{algorithm}
\end{document}]

Desired output:

output

Is there a proper way to do this? What about making the comment italicized so that it's a little less intrusive?

2

2 Answers 2

1

I fixed some errors in the code:

  • replaced the 2 occurrences of \[...\] with [...]
  • deleted the last character ]

I added the \textit command to get the comment italicized.

\documentclass{article}
\usepackage{amsmath}
\usepackage{caption}
\usepackage{algpseudocode}
\usepackage{algorithm}
\captionsetup[algorithm]{labelformat=empty}

\begin{document}
    \begin{algorithm}
        \caption{Init}
        \begin{algorithmic}[1]
            \State // \textit{Here is a comment the way I want it.}
            \State $x \gets y$
        \end{algorithmic}
    \end{algorithm}
\end{document}

enter image description here

You could also define a command for your comment type (\CommentLine):

\documentclass{article}
\usepackage{amsmath}
\usepackage{caption}
\usepackage{algpseudocode}
\usepackage{algorithm}
\captionsetup[algorithm]{labelformat=empty}

\newcommand{\CommentLine}[1]{
    \State // \textit{#1}
}

\begin{document}
    \begin{algorithm}
        \caption{Init}
        \begin{algorithmic}[1]
            \CommentLine{Here is a comment the way I want it.}
            \State $x \gets y$
        \end{algorithmic}
    \end{algorithm}
\end{document}
1

Redefine the way algorithmicx's \Comment works using

\algrenewcommand\algorithmiccomment[1]{// {\itshape #1}}

The default behaviour is to insert \hfill \(\triangleright\), which puts the comment flush with the right margin.

enter image description here

\documentclass{article}

\usepackage{algpseudocode,algorithm}

\usepackage{caption}
\captionsetup[algorithm]{labelformat=empty}

\algrenewcommand\algorithmiccomment[1]{// {\itshape #1}}

\begin{document}

\begin{algorithm}
  \caption{Init}
  \begin{algorithmic}[1]
    \State // Here is a comment the way I want it.
    \State $x \gets y$
    \State \Comment{Here is a comment the way I want it.}
    \end{algorithmic}
  \end{algorithm}

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.