算法的一部分的引用

算法的一部分的引用

我想写一篇关于算法分析的文章。根据某些条件,会出现多种情况。我想引用这些案例,但不是完全基于在线号码. 本质上我想要与 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提供设置自定义行号的方法\nlset通过以下常规方式引用它们\label

在此处输入图片描述

\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}

答案2

您可以通过创建自定义计数器来实现这一点:

\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}

在这个 MWE 中,\case{}命令既增加cases计数器,又根据该计数器标记案例。

相关内容