演算法中的程式碼行縮排

演算法中的程式碼行縮排

我正在編寫有兩個階段的演算法。如何縮排第一階段和第二階段的程式碼?

\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

貢薩洛的答案的問題在於編號,因為數字也是縮排的。

\algorithmic為內建環境找到了更好、更簡單的解決方案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。第一個建立縮排,第二個建立負縮排,從而刪除先前建立的縮排。看這個答案更多細節。

相關內容