1

I am writing a pseudocode/an algorithm. When writings comments, they are aligned to the right. This is really inconvenient as some of my comments are very long and take multiple lines. In addition, it is somewhat challenging to make a difference between the code and comments.

My algorithm is very long and requires multiple pages; thus, I had to split it into multiple blocks.

Here is an example:

\usepackage{algorithm,algpseudocode}
\usepackage{caption}

\algrenewcommand\algorithmicrequire{\textbf{Input:}}
\algrenewcommand\algorithmicensure{\textbf{Output:}}

\begin{algorithm}
\caption{$y = f(x)$}
\label{my_algorithm}

\begin{algorithmic}[1]
\Require \strut $x_0$
\Ensure $y$
\State $x \gets x_0$
\State $y \gets x^2$ \Comment{This is a very long comment and it would be nice if it would have its own line. It could also be written in a different colour.}
\State  $x_1 \gets y$
\algstore{myalg}
\end{algorithmic}
\end{algorithm}

There is a page break between different blocks of code, but the algorithm continues:

\begin{algorithm}
\addtocounter{algorithm}{-1}
\begin{algorithmic}[1]
\algrestore{myalg}
\State\strut  $x \gets x_1$ \Comment{We continue here from where we left. It would be convenient to have the comment in its own line before the variable declaration.}
\State $y = x^2$
\end{algorithmic}
\end{algorithm}

Now the code looks like: enter image description here

How could I make the comments have their own lines, and maybe different colour from the code?

1 Answer 1

1
\documentclass{article}
\usepackage{algorithm}
\usepackage[beginLComment=/*~,endLComment=~*/]{algpseudocodex}
\algrenewcommand{\algorithmicrequire}{\textbf{Input:}}
\algrenewcommand{\algorithmicensure}{\textbf{Output:}}
\begin{document}
\begin{algorithm}
\caption{$y = f(x)$}
\label{my_algorithm}
\begin{algorithmic}[1]
\Require \strut $x_0$
\Ensure $y$
\State $x \gets x_0$
\State $y \gets x^2$ \LComment{\color{red} This is a very long comment and it would be nice if it would have its own line. It could also be written in a different colour.}
\State  $x_1 \gets y$
\algstore{myalg}
\end{algorithmic}
\end{algorithm}
There is a page break between different blocks of code, but the algorithm continues:
\begin{algorithm}
\addtocounter{algorithm}{-1}
\begin{algorithmic}[1]
\algrestore{myalg}
\State\strut  $x \gets x_1$ \LComment{We continue here from where we left. It would be convenient to have the comment in its own line before the variable declaration.}
\State $y = x^2$
\end{algorithmic}
\end{algorithm}
\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .