[Tex/LaTex] Change line numbering in algorithmics package

algorithmicxline-numbering

I would like to start the line numbering of the following code not from 1 but from 12 (as it is cut out of a larger code). So it should be 12,13,14,15 instead of 1,2,3,4.

\documentclass{article}
\usepackage{algorithm}
\usepackage[noend]{algpseudocode}
\begin{document}

\begin{algorithm}[h]
  \begin{algorithmic}[1]
    \If{$(w,s')$ not in $Q$}                      \Comment{insert}
      \State $k(w,s')  \gets d_{r}(w,s') + \pi_{w,s'}$
    \Else                                        \Comment{decrease}
      \State $k(w,s') \gets d_{r}(w,s')+ \pi_{w,s'}$
    \EndIf
  \end{algorithmic}
\end{algorithm}

\end{document}

enter image description here

Best Answer

Set the ALG@line counter to the desired value:

\documentclass{book}
\usepackage{algorithm,algpseudocode}

\begin{document}

\begin{algorithm}[h]
  \begin{algorithmic}[1]
\makeatletter
\setcounter{ALG@line}{11}
\makeatother
    \If{$(w,s')$ not in $Q$}                      \Comment{insert}
      \State $k(w,s')  \gets d_{r}(w,s') + \pi_{w,s'}$
    \Else                                        \Comment{decrease}
      \State $k(w,s') \gets d_{r}(w,s')+ \pi_{w,s'}$
    \EndIf
  \end{algorithmic}
\end{algorithm}

\end{document}

A better approach would be to use \algstore and \algrestore since this mechanism automatically saves the line number, indentation, open blocks of the current algorithm and closes all blocks; please refer to Section 2.6 Breaking up long algorithms of the algorithmicx documentation.

Related Question