[Tex/LaTex] How to hide specific line numbers in an algorithm

algorithm2ealgorithmsline-numbering

I use the algorithm2e-package with option "linesnumbered". Now every line gets a number, but I would like to number only special lines. For example the second and fifth line.

\documentclass[12pt,a4paper]{article}

\usepackage[utf8]{inputenc}

\usepackage{amssymb}

\usepackage[vlined,linesnumbered,ruled,resetcount]{algorithm2e}

\SetKwBlock{Repeat}{repeat}{}

\SetKwInOut{Initialization}{Initialization}

\begin{document}

\begin{algorithm}[H]

\caption{Test algorithm}

\Initialization{Set $U=\infty$}

\While{($\exists$ pending nodes in the tree)}{

    Select an unexplored node. \\

    \Repeat (\{iteration\}){

        Solve problem (5). \\

    \eIf{(5) infeasible}{fathome node.}

      {$(x^{(k+1)},y^{(k+1)})=(x^{(k)},y^{(k)})+(d_x^{(k)},d_y^{(k)})$.}}}
\end{algorithm}

\end{document}

Best Answer

Two variants: number the lines according to their position (2nd line = 2, 5th line = 5), or number the lines sequentially (2nd line = 1, 5th line = 2).

The first variant sets hidden numbers and shows the number for selected lines. Note that the Initialization statement is not numbered, this is by design of algorithm2e (replace the line by \textbf{Initialization} Set $U=\infty$\\ if you want this numbered as well).

\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amssymb}
\usepackage[vlined,linesnumberedhidden,ruled,resetcount]{algorithm2e}

\SetKwBlock{Repeat}{repeat}{}
\SetKwInOut{Initialization}{Initialization}

\begin{document}
\begin{algorithm}[H]
\caption{Test algorithm}
\Initialization{Set $U=\infty$}
\While{($\exists$ pending nodes in the tree)}{
    \ShowLn
    Select an unexplored node. \\
    \Repeat (\{iteration\}){
        Solve problem (5). \\
    \ShowLn
    \eIf{(5) infeasible}{fathome node.}
      {$(x^{(k+1)},y^{(k+1)})=(x^{(k)},y^{(k)})+(d_x^{(k)},d_y^{(k)})$.}}}
\end{algorithm}
\end{document}

enter image description here

The second variant switches of the numbering and, for selected lines, manually increases the algorithm line counter and shows the number.

\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amssymb}
\usepackage[vlined,linesnumbered,ruled,resetcount]{algorithm2e}

\SetKwBlock{Repeat}{repeat}{}
\SetKwInOut{Initialization}{Initialization}

\newcommand{\nextnr}{\stepcounter{AlgoLine}\ShowLn}

\begin{document}
\LinesNotNumbered
\begin{algorithm}[H]
\caption{Test algorithm}
\Initialization{Set $U=\infty$}
\While{($\exists$ pending nodes in the tree)}{
    \nextnr
    Select an unexplored node. \\
    \Repeat (\{iteration\}){
        Solve problem (5). \\
    \nextnr
    \eIf{(5) infeasible}{fathome node.}
      {$(x^{(k+1)},y^{(k+1)})=(x^{(k)},y^{(k)})+(d_x^{(k)},d_y^{(k)})$.}}}
\end{algorithm}
\end{document}

enter image description here