如何将自定义标签放入算法环境中?

如何将自定义标签放入算法环境中?

algorithms我正在尝试一种对算法 1a、1b、1c、2a、2b、2c 等进行编号的方法。据我从该包的文档中了解这里,我可以在部分、章节、节等之后给它们编号。在相关主题他们讨论了如何自定义数字。但我不想要数字,我还想有字母:例如,在下面的 MWE 中,我想将这两个算法编号(因此引用为)1a 和 1b。

\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}
Algorithm~\ref{MyAlg} does things in a way. Algorithm~\ref{MyOtherAlg} does things in some other way.
\begin{algorithm}\caption{My algorithm}\label{MyAlg}
\begin{algorithmic}[1]
\State Do stuff.
\end{algorithmic}
\end{algorithm}
\begin{algorithm}\caption{My other algorithm}\label{MyOtherAlg}
\begin{algorithmic}[1]
\State Do stuff differently.
\end{algorithmic}
\end{algorithm}
\end{document}

有什么想法可以实现这个目标吗?

答案1

您所要做的就是重新定义\thealgorithm控制算法计数器表示的命令。例如,使用字母小写字符对它们进行编号并在前面添加节号,您需要执行

\renewcommand\thealgorithm{\thesection\alph{algorithm}}

假设您希望计数器在每个部分重置,您还需要

\usepackage{chngcntr}
\counterwithin{algorithm}{section}

一个完整的例子。

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

\counterwithin{algorithm}{section}
\renewcommand\thealgorithm{\thesection\alph{algorithm}}

\begin{document}
\section{Test section}

Algorithm~\ref{MyAlg} does things in a way. Algorithm~\ref{MyOtherAlg} does things in some other way.
\begin{algorithm}\caption{My algorithm}\label{MyAlg}
\begin{algorithmic}[1]
\State Do stuff.
\end{algorithmic}
\end{algorithm}
\begin{algorithm}\caption{My other algorithm}\label{MyOtherAlg}
\begin{algorithmic}[1]
\State Do stuff differently.
\end{algorithmic}
\end{algorithm}

\end{document}

结果:

在此处输入图片描述

更新:

如果要使用用户定义的计数器,想法也是一样:

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

\newcounter{mycount}
\counterwithin{algorithm}{mycount}
\refstepcounter{mycount}
\renewcommand\thealgorithm{\arabic{mycount}\alph{algorithm}}

\begin{document}
\section{Test section}

Algorithm~\ref{MyAlg} does things in a way. Algorithm~\ref{MyOtherAlg} does things in some other way.
\begin{algorithm}\caption{My algorithm}\label{MyAlg}
\begin{algorithmic}[1]
\State Do stuff.
\end{algorithmic}
\end{algorithm}
\begin{algorithm}\caption{My other algorithm}\label{MyOtherAlg}
\begin{algorithmic}[1]
\State Do stuff differently.
\end{algorithmic}
\end{algorithm}

\end{document}

或者使用大写字母进行编号:

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

\renewcommand\thealgorithm{\Alph{algorithm}}

\begin{document}
\section{Test section}

Algorithm~\ref{MyAlg} does things in a way. Algorithm~\ref{MyOtherAlg} does things in some other way.
\begin{algorithm}\caption{My algorithm}\label{MyAlg}
\begin{algorithmic}[1]
\State Do stuff.
\end{algorithmic}
\end{algorithm}
\begin{algorithm}\caption{My other algorithm}\label{MyOtherAlg}
\begin{algorithmic}[1]
\State Do stuff differently.
\end{algorithmic}
\end{algorithm}

\end{document}

结果:

在此处输入图片描述

相关内容