我想在算法包中添加两个自定义项:引入一个新的 break 命令,并可以为 LOOP 提供标签,以便break {label}
清楚地了解所指的循环。我尝试像这样引入 break 命令:
\newcommand{\algorithmicbreak}{\textbf{break}}
但这不起作用,当我输入时,我收到未知命令错误\BREAK
然而,通过这个技巧我可以让它工作,但它非常不好看:
\renewcommand{\algorithmicprint}{\textbf{break}}
% then use it as
\PRINT
LOOP 标签我不知道如何介绍。
更新:我的完整示例
\begin{algorithm}
\renewcommand{\algorithmicrequire}{\textbf{Input:}}
\renewcommand{\algorithmicensure}{\textbf{Output:}}
\renewcommand{\algorithmicprint}{\textbf{break}}
\caption{\text{My-Algorithm}}
\label{algo:blah}
\begin{algorithmic}[1]
\REQUIRE X
\ENSURE Y
% STEP 1
\STATE \COMMENT{{\bf Step 1}} some something
\LOOP % can't annotate the loop :(((
% STEP 2
\STATE \COMMENT{{\bf Step 2}} do something more
\IF {$a = b$}
\RETURN $c$
\ELSE
\LOOP % can't annotate the loop :(((
% STEP 3
\STATE \COMMENT{{\bf Step 3}} do some more
\IF {$b = c$}
\STATE $y = x$
\PRINT % intending to break
\ELSE
% STEP 4
\STATE \COMMENT{{\bf Step 4}} and yet some more
\ENDIF
\ENDLOOP
\ENDIF
\ENDLOOP
\end{algorithmic}
\end{algorithm}
答案1
这是添加到algorithmic
这使得你可以\BREAK
和有一个带注释的循环\ALOOP
(和\ENDALOOP
)。它基于常规\LOOP
和\ENDLOOP
组合的副本,并添加了注释参数。当然,可以进行更多修改:
\documentclass{article}
\usepackage{algorithm,algorithmic}% http://ctan.org/pkg/algorithms
% Algorithmic modifications
\makeatletter
\newcommand{\ALOOP}[1]{\ALC@it\algorithmicloop\ #1%
\begin{ALC@loop}}
\newcommand{\ENDALOOP}{\end{ALC@loop}\ALC@it\algorithmicendloop}
\renewcommand{\algorithmicrequire}{\textbf{Input:}}
\renewcommand{\algorithmicensure}{\textbf{Output:}}
\newcommand{\algorithmicbreak}{\textbf{break}}
\newcommand{\BREAK}{\STATE \algorithmicbreak}
\makeatother
\begin{document}
\begin{algorithm}
\caption{My-Algorithm}\label{algo:blah}
\begin{algorithmic}[1]
\show\LOOP
\REQUIRE X
\ENSURE Y
% STEP 1
\STATE \COMMENT{\textbf{Step 1}} some something
\ALOOP {outer} % Outer loop
% STEP 2
\STATE \COMMENT{\textbf{Step 2}} do something more
\IF {$a = b$}
\RETURN $c$
\ELSE
\ALOOP {inner} % Inner loop
% STEP 3
\STATE \COMMENT{\textbf{Step 3}} do some more
\IF {$b = c$}
\STATE $y = x$
\BREAK % intending to break
\ELSE
% STEP 4
\STATE \COMMENT{\textbf{Step 4}} and yet some more
\ENDIF
\ENDALOOP
\ENDIF
\ENDALOOP
\end{algorithmic}
\end{algorithm}
\end{document}
如果您也想注释它,那么也可以修改\BREAK
它以采用一个参数(比如说,跳出一个特定的循环)。
为了完整性,我已修复了你的 用法\bf
。因此,请参阅\textit
我使用或\it
或\bfseries
等有关系吗\bf
?和两个字母的字体样式命令(\bf
,,\it
...)会在 LaTeX 中复活吗?
答案2
如果你使用algoritmicx 包,它具有更多功能,并且可以与其他软件包更好地配合:
\documentclass[12pt]{report}
\usepackage[a4paper,tmargin=1.25in, bmargin=1.25in, lmargin=1.25in, rmargin=1.25in]{geometry}
\usepackage{algpseudocode}
\newcommand{\Break}{\State \textbf{break} }
\algblockdefx[Loop]{Loop}{EndLoop}[1][]{\textbf{Loop} #1}{\textbf{End Loop}}
\begin{document}
Here is an example:
\begin{algorithmic}[1]
\Require Integers $a >0$ and $b$
\Ensure $a\cdot b$
\State $i\leftarrow 0$
\State $c \leftarrow 0$
\Loop{1}
\If{$i=a$}
\Break Loop 1
\EndIf
\State $c \leftarrow c + b$
\State $i \leftarrow i + 1$
\EndLoop
\State \textbf{return} $c$
\end{algorithmic}
\end{document}