[Tex/LaTex] How to have the algorithmicx comment symbol in algorithm2e

algorithm2ealgorithmicx

I want to know how can I have the nice ▷
$\triangleright$ comment symbol of algorithmicx in algorithm2e?

Best Answer

From the algorithm2e documentation (section 11.4 to define comments, p 35):

\SetKwComment{Comment}{<start>}{<end>} defines a macro \Comment{text comment} which writes text comment between <start> and <end>. Note that <start> or <end> can be empty.

It defines also \Comment*{side comment text} macro which allows to put comment on the same line as the code. This macro can take various option to control its behaviour:

  • \Comment*[r]{side comment text} put the end of line mark (; by default) and side comment text just after and right justified, then end the line. It is the default.

  • \Comment*[l]{side comment text} same thing but side comment text is left justified.

  • \Comment*[h]{side comment text} put side comment right after the text. No end of line mark is put, and line is not terminated (is up to you to put \; to end the line).

  • \Comment*[f]{side comment text} same as the previous one but with side comment text right justified.

Here's an example of the above:

enter image description here

\documentclass{article}
\usepackage{algorithm2e}
\SetKwComment{Comment}{$\triangleright$\ }{}
\begin{document}

\begin{algorithm}[H]
  \SetAlgoLined
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
  initialization\;
  \While{not at end of this document}{
    read current\;
    \eIf{understand}{
      go to next section \Comment*[r]{Some comment}
      current section becomes this one\;
    }{
      go back to the beginning of current section\;
    }
  }
  \caption{How to write algorithms}
\end{algorithm}

\end{document}

If you wish to reformat the comment font, you can adjust \CommentSty. In algorithm2e this is done via (for example) \SetCommentSty{itshape} to obtain an \itshape or italics comment.


Here is a corresponding example showing the default comment style in algorithmicx, taken directly from the algorithmicx documentation:

enter image description here

\documentclass{article}
\usepackage{algorithm,algpseudocode}
\begin{document}

\begin{algorithm}
  \caption{Euclid’s algorithm}\label{euclid}
  \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
      \State $r\gets a\bmod b$
      \While{$r\not=0$}\Comment{We have the answer if r is 0}
        \State $a\gets b$
        \State $b\gets r$
        \State $r\gets a\bmod b$
      \EndWhile\label{euclidendwhile}
      \State \textbf{return} $b$\Comment{The gcd is b}
    \EndProcedure
  \end{algorithmic}
\end{algorithm}

\end{document}