如何在算法中放置带有级别的行号?

如何在算法中放置带有级别的行号?
\documentclass[a4paper, 10pt, 3p, final, twocolumn, times]{elsarticle}
\usepackage{algorithm}
\usepackage{algorithmic}
\begin{document}
\begin{algorithm}[htbp]
    \caption{somealg}
    \label{alg}
    \begin{algorithmic}[1]
    \REQUIRE input
    \ENSURE output
    \STATE statement 1
    \FOR {i = 1 to $l$}
    \STATE statement in loop 1
    \STATE statement in loop
    \ENDFOR
    \end{algorithmic}
    \end{algorithm}
\end{document}

我想在我的算法中添加行号,“for”循环内的语句的行号应该是2.1而不是3。我该怎么做?谢谢。

答案1

以下不允许循环结构相互嵌套,但提供了伪代码分组的子编号(如、\FOR\WHILE):\LOOP\REPEAT

在此处输入图片描述

\documentclass{article}

\usepackage{algorithm,algorithmic,xpatch}

\makeatletter
\xpatchcmd{\algorithmic}% <cmd>
  {\arabic{ALC@line}}% <search>
  {\theALC@line}% <replace>
  {}{}% <success><failure>
\xpatchcmd{\algorithmic}{1.2em}{1.5em}{}{}% Increase label width

\newcommand{\updatelinenoprint}{%
  \setcounter{parentcounter}{\value{ALC@line}}% Store current line number
  \setcounter{ALC@line}{0}% Restart line counter
  \renewcommand{\theALC@line}{\theparentcounter.\arabic{ALC@line}}% Update printing mechanism
}
\newcommand{\revertlinenoprint}{%
  \setcounter{ALC@line}{\value{parentcounter}}% Restore original line number
}%

\renewcommand{\theALC@line}{\arabic{ALC@line}}
\newcounter{parentcounter}
\xapptocmd{\algorithmic}{%
  \xapptocmd{\ALC@for}{\updatelinenoprint}{}{}\xpretocmd{\endALC@for}{\revertlinenoprint}{}{}%
  \xapptocmd{\ALC@whl}{\updatelinenoprint}{}{}\xpretocmd{\endALC@whl}{\revertlinenoprint}{}{}%
  \xapptocmd{\ALC@loop}{\updatelinenoprint}{}{}\xpretocmd{\endALC@loop}{\revertlinenoprint}{}{}%
  \xapptocmd{\ALC@rpt}{\updatelinenoprint}{}{}\xpretocmd{\endALC@rpt}{\revertlinenoprint}{}{}%
}
\makeatother

\begin{document}

\begin{algorithm}[htbp]
  \caption{somealg}
  \begin{algorithmic}[1]
    \REQUIRE input
    \ENSURE output
    \STATE statement 1
    \FOR {$i = 1$ to $l$}
      \STATE statement in loop 1
      \STATE statement in loop
    \ENDFOR
    \STATE statement 2
    \WHILE {$i < 10$}
      \STATE statement in loop 1
      \STATE statement in loop
    \ENDWHILE
  \end{algorithmic}
\end{algorithm}

\end{document}

相关内容