我有一个算法太长,一页都放不下。有人建议手动拆分算法,然后更改第二个算法的行号以跟上第一个算法。我知道\begin{algorithmic}[1]
每行一个数字,而\begin{algorithmic}[5]
每五行一个数字。如何将起始数字从“1”更改为其他数字?
答案1
以下最小示例展示了如何修改算法的起始行号。在环境中algorithmic
,添加代码
\makeatletter\setcounter{ALG@line}{<n>}\makeatother
其中<n>
比第一个行号小一。原因是该\State
命令先增加计数器,然后再排版。
\documentclass{article}
\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx
\begin{document}
\begin{algorithmic}[1]
\makeatletter\setcounter{ALG@line}{5}\makeatother
\State Here is some code
\State Here is another line of code
\State And then some more
\end{algorithmic}
\end{document}
当然,这假设你正在使用(更高级的)algorithmicx
包裹排版您的algorithmic
环境。
如果你想让这个过程更方便一些,这是可能的。例如,你可以\State
通过提供一个可选命令来重新定义来为你执行此操作:
\documentclass{article}
\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx
\usepackage{xparse}% http://ctan.org/pkg/xparse
\let\oldState\State% Store \State in \oldState
\RenewDocumentCommand{\State}{o}{% \State[<num>]
\IfValueTF{#1}{\makeatletter\setcounter{ALG@line}{#1}\addtocounter{ALG@line}{-1}\makeatother}{}%
\oldState\ignorespaces%
}%
\begin{document}
\begin{algorithmic}[1]
\State[8] Here is some code
\State Here is another line of code
\State And then some more
\State[5] and a last line of code
\end{algorithmic}
\end{document}
\State
重新定义的接口\State[<num>]
由xparse
。
请注意,如果您计划将单个algorithmic
环境拆分到多个页面,algorithmicx
则还提供\algstore{<name>}
选项\algrestore{<name>}
。这是一个简短的示例:
\documentclass{article}
\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx
\begin{document}
\begin{algorithmic}[1]
\State Here is some code
\State Here is another line of code
\algstore{myalg}% Save algorithm
\end{algorithmic}
\hrule
\begin{algorithmic}[1]
\algrestore{myalg}% Restore algorithm
\State And then some more
\State and a last line of code
\end{algorithmic}
\end{document}