1

I use tabular inside algorithm environment of algorithm2e package (see figure below) in order to align two columns of comment lines. Without using a table, achieving this task is difficult with some other methods suggested here.

enter image description here

\documentclass{article}
\usepackage{amsmath}
\usepackage[vlined, ruled, noend]{algorithm2e}

\begin{document}
\begin{algorithm}
    \LinesNumbered

    \SetKwInOut{Input}{Input}
    \SetKwInOut{Output}{Output}

    \Input{$A$}
    \Output{$C$}

    \BlankLine

    \If {condition}{
        \begin{tabular}{@{\hspace{0em}}p{0.3\linewidth}p{0.4\linewidth}l}
            \noalign{\vskip2pt}
            $B \gets A$ & Comments & Flops \\
            $C \gets B$ & Comments & Flops \\
            \multicolumn{3}{@{\hspace{0em}}l}{\KwRet $C$} \\
        \end{tabular}
    }
    \caption{Computing $C$}
\end{algorithm}
\end{document}

Despite the convenient of using a table, its downside is that the algorithm environment count each table as one line. For example, in the above figure, all three rows of the table are counted as line 2. Is there any way to modify line counter of algorithm2e to count table rows?

1 Answer 1

1

Based on your example, you can just place the elements in boxes of fixed width and they should align as needed:

enter image description here

\documentclass{article}

\usepackage{amsmath}
\usepackage[vlined, ruled, noend]{algorithm2e}

\begin{document}

\begin{algorithm}
  \LinesNumbered

  \SetKwInOut{Input}{Input}
  \SetKwInOut{Output}{Output}

  \Input{$A$}
  \Output{$C$}

  \BlankLine

  \If {condition}{
    \begin{tabular}{@{\hspace{0em}}p{0.3\linewidth}p{0.4\linewidth}l}
      \noalign{\vskip2pt}
        $B \gets A$ & Comments & Flops \\
        $C \gets B$ & Comments & Flops \\
        \multicolumn{3}{@{\hspace{0em}}l}{\KwRet $C$} \\
      \end{tabular}
  }
  \caption{Original: Computing $C$}
\end{algorithm}

\begin{algorithm}
  \LinesNumbered
  \DontPrintSemicolon

  \SetKwInOut{Input}{Input}
  \SetKwInOut{Output}{Output}

  \Input{$A$}
  \Output{$C$}

  \BlankLine

  \If {condition}{
    \makebox[0.3\linewidth][l]{$B \gets A$}%
      \makebox[0.4\linewidth][l]{Comments}%
      Flops\;
    \makebox[0.3\linewidth][l]{$C \gets B$}%
      \makebox[0.4\linewidth][l]{Comments}%
      Flops\;
    \KwRet $C$\;
  }
  \caption{Updated: Computing $C$}
\end{algorithm}

\end{document}

You must log in to answer this question.

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