參考演算法的一部分

參考演算法的一部分

我想寫一篇關於演算法的分析。根據某些條件,會出現多種情況。我想參考案例,但是不是完全基於在行號上。本質上我想要與 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計數器又根據該計數器標記案例。

相關內容