1

I need to have references in some algorithms and for this I want to have a command which can take 3 parameters, the first being the key of the algorithm and the second and third being options for lines within the algorithm. If the command name is algoref, I need that \algoref{key} generate the code A.~\ref{#1} if the second parameter is empty. If the second parameter is not empty, it generates A.~\ref{#1},L.#2 and if the second and third parameter isn't empty, it generates A.~\ref{#1},L.#2:#3. Is that possible ?

  • 1
    Would \algoref{key}, \algoref[3]{key} and \algoref[3-5]{key} satisfy your wish? – egreg Nov 2 '17 at 9:28
  • yeah that would be perfect – Noor Nov 2 '17 at 9:36
2

Here's the implementation: the syntax is

\algoref{key} for “A. 1”
\algoref[3]{key} for “A. 1, L. 3”
\algoref[4-6}{key} for “A. 1, L. 4:6”

\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\usepackage{xparse}

\NewDocumentCommand{\algoref}{om}{%
  % main reference
  A.~\ref{#2}%
  % check for the optional argument
  \IfValueT{#1}{,~L.~\algolines{#1}}%
}
\NewDocumentCommand{\algolines}{>{\SplitArgument{1}{-}}m}{%
  % check for a hyphen
  \algolinessplit#1%
}
\NewDocumentCommand{\algolinessplit}{mm}{%
  % first or unique line number
  #1%
  % second line number, if given
  \IfValueT{#2}{:#2}%
}

\begin{document}

\begin{algorithm}
\caption{Euclid’s algorithm}\label{euclid}
\begin{algorithmic}[1]
\Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
   \State $r\gets a\bmod b$
   \While{$r\not=0$}\Comment{We have the answer if r is 0}
      \State $a\gets b$
      \State $b\gets r$
      \State $r\gets a\bmod b$
   \EndWhile\label{euclidendwhile}
   \State \textbf{return} $b$\Comment{The gcd is b}
\EndProcedure
\end{algorithmic}
\end{algorithm}

References: \algoref{euclid}, \algoref[3]{euclid}, \algoref[1-4]{euclid}

\end{document}

I used algpseudocode, but actually any package should do.

enter image description here

  • 1
    @Noor If you also label lines, you can use \algoref[\ref{start}-\ref{end}]{key} – egreg Nov 2 '17 at 9:59
  • is it possible to eliminate the space caused by the tilde, e.g. A.1 instead of A. 1, removing the tilde makes it but this can have an affect on how the notation is placed is the next, is there a better solution ? – Noor Nov 2 '17 at 10:19
  • @Noor Just remove ~ – egreg Nov 2 '17 at 10:46

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.