算法中的代码行缩进

算法中的代码行缩进

我正在编写包含两个阶段的算法。如何缩进第一阶段和第二阶段的代码?

\begin{algorithm}[H]
\caption*{my algorithm}
\begin{algorithmic}
    \STATE \textbf{Stage one:} this is stage one
    \FORALL{i}
        \STATE do something
    \ENDFOR
    \STATE \textbf{Stage two:} this is stage two
    \STATE Update the trie: 
    \FORALL{j}
    \STATE do something
    \ENDFOR
\end{algorithmic}
\end{algorithm}

答案1

在下面的示例代码中,我定义了两个新命令,允许您更改缩进;只需使用 , 括起所需的片段\bindent\eindent长度\myindent控制缩进量:

\documentclass{article}
\usepackage{algorithm,algorithmic}
\usepackage{caption}

\newlength\myindent
\setlength\myindent{2em}
\newcommand\bindent{%
  \begingroup
  \setlength{\itemindent}{\myindent}
  \addtolength{\algorithmicindent}{\myindent}
}
\newcommand\eindent{\endgroup}

\begin{document}

\begin{algorithm}[H]
\caption*{my algorithm}
\begin{algorithmic}
    \STATE \textbf{Stage one:} this is stage one
    \bindent
    \FORALL{i}
        \STATE do something
    \ENDFOR
    \eindent
    \STATE \textbf{Stage two:} this is stage two
    \bindent
    \STATE Update the trie: 
    \FORALL{j}
    \STATE do something
    \ENDFOR
    \eindent
\end{algorithmic}
\end{algorithm}

\end{document}

在此处输入图片描述

对代码的一些注释:

\newlength\myindent % define a new length \myindent
\setlength\myindent{6em} % assign the length 2em to \myindet
\newcommand\bindent{%
  \begingroup % starts a group (to keep changes local)
  \setlength{\itemindent}{\myindent} % set itemindent (algorithmic internally uses a list) to the value of \mylength
  \addtolength{\algorithmicindent}{\myindent} % adds \mylength to the default indentation used by algorithmic
}
\newcommand\eindent{\endgroup} % closes a group

答案2

定义:

\algdef{SE}[SUBALG]{Indent}{EndIndent}{}{\algorithmicend\ }%
\algtext*{Indent}
\algtext*{EndIndent}

然后在算法块中写入:

\begin{algorithmic}[1]
    \State Outside indent block
    \Indent
         \State Inside indent block
    \EndIndent
\end{algorithmic}

答案3

贡萨洛 (Gonzalo) 的答案存在问题,因为数字也是缩进的。

\algorithmic为inbuild 环境找到了更好、更简单的解决方案ALC@g

\begin{ALC@g}
   % Indent what you need
\end{ALC@g}

在同一文档中进行比较

\newlength\myindent
\setlength\myindent{2em}
\newcommand\bindent{%
    \begingroup
    \setlength{\itemindent}{\myindent}
    \addtolength{\algorithmicindent}{\myindent}
}
\newcommand\eindent{\endgroup}

\begin{algorithmic}[1]
    \STATE \textbf{Gonsalo's answer}
    \bindent
    \STATE First
    \STATE Second 
    \eindent
    \STATE \textbf{Proposed answer}

    \begin{ALC@g}
        \STATE First
        \STATE Second 
    \end{ALC@g}
    \STATE Something else
\end{algorithmic}

结果

测试

当然,您可以在我的提案中包含更大缩进的解决\addtolength方案\setlength

答案4

如果你使用该algorithm2e包,答案\Indp\Indm。第一个创建缩进,第二个创建负缩进,从而删除先前创建的缩进。参见这个答案更多细节。

相关内容