알고리즘에서 코드 줄 들여쓰기

알고리즘에서 코드 줄 들여쓰기

저는 두 단계로 구성된 알고리즘을 작성 중입니다. 1단계와 2단계의 코드를 어떻게 들여쓰나요?

\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내장 환경 에 대한 더 좋고 간단한 솔루션을 찾았습니다.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. 첫 번째는 들여쓰기를 생성하고 두 번째는 음수 들여쓰기를 생성하여 이전에 생성된 것을 제거합니다. 보다이 답변상세 사항은.

관련 정보