1

I would like to write about the analysis of an algorithm. Depending on some conditions multiple cases arise. I would like to reference the cases but not solely based on the line numbers. Essentially I want custom labels which work with hyperref.

\documentclass{article}

\usepackage{algorithm2e}

\begin{document}

\vspace{2em}

\begin{algorithm}[H]
\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 \tcp*[f]{Case (1)} \;
current section becomes this one\;
}{
go back to the beginning of current section\;
}
}
\end{algorithm}

Analyis: Consider Case (1).

\end{document}
1

algorithm2e provides the means to set custom line numbers and reference them via \nlset together with a regular \label:

enter image description here

\documentclass{article}

\usepackage{algorithm2e}
\newcommand{\algcaseref}{Case~\ref}

\begin{document}

\begin{algorithm}[H]
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
  initialization\;
  \While{not at end of this document}{
    read current\;
    \eIf{understand}{
      \nlset{(1)}\label{case:1}go to next section\;
      current section becomes this one\;
    }{
      \nlset{(B)}\label{case:2}go back to the beginning of current section\;
    }
  }
\end{algorithm}

Analysis: Consider \algcaseref{case:1}. Also consider \algcaseref{case:2}.

\end{document}
0

You could do this by creating a custom counter:

\documentclass{article}

\usepackage{algorithm2e}
\usepackage{hyperref}

\newcounter{cases}
\newcommand{\case}[1]{\refstepcounter{cases}\label{#1}}

\begin{document}

\vspace{2em}

\begin{algorithm}[H]
\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 \tcp*[f]{Case (1)} \case{mycase} \;
current section becomes this one\;
}{
go back to the beginning of current section\;
}
}
\end{algorithm}

Analyis: Consider Case (\ref{mycase}).

\end{document}

In this MWE, the \case{} command both increases the cases counter and labels the case according to that counter.

  • Well, I don't actually need any numbering at all. I just want a label that I can reference. It just needs to work properly with hyperref, i.e. when I click on the reference I get shown the relevant part of the algorithm – hfhc2 Feb 10 '16 at 16:37
  • @hfhc2 I'm not sure what you mean. If you load the hyperref package, clicking on the label (1) will take you to the relevant part of the algorithm. – LSchoon Feb 10 '16 at 16:39
  • I added the inclusion of hyperref to my MWE. – LSchoon Feb 10 '16 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.