如何在算法中正确换行

如何在算法中正确换行

我在显示算法时遇到了问题。包装真的很丑,我无论如何也找不到不需要手动调整所有内容的解决方法,以至于我还不如放弃那些蹩脚的算法包,用 TeX 写出所有内容。

有什么方法可以正确缩进以下内容

\documentclass{article}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}
\begin{algorithm}
   \caption{My pseudo code.}
\begin{algorithmic}[1]
   \While{this line is sooooooooooo long and boring and too much for algorithmic to handle}
      \State look at this state, this state is just too long for algorithmic to display it properly 
      \While{again this line is sooooooooooo long and boring and too much for algorithmic too handle}
         \State look at this state again, this state is just too long for algorithmic to handle, I'm just going to switch to Word
      \EndWhile
   \EndWhile
\end{algorithmic}
\end{algorithm}
\end{document}​

丑陋的算法

这样输出类似于

漂亮算法

答案1

algorithmicx显然,它的目的不是将段落样式的文本作为伪代码的一部分进行管理。您必须自己做一些准备工作,才能让它复制您的要求:

在此处输入图片描述

\documentclass{article}
\usepackage{algorithm,algpseudocode}
\makeatletter
\newcommand{\algmargin}{\the\ALG@thistlm}
\makeatother
\newlength{\whilewidth}
\settowidth{\whilewidth}{\algorithmicwhile\ }
\algdef{SE}[parWHILE]{parWhile}{EndparWhile}[1]
  {\parbox[t]{\dimexpr\linewidth-\algmargin}{%
     \hangindent\whilewidth\strut\algorithmicwhile\ #1\ \algorithmicdo\strut}}{\algorithmicend\ \algorithmicwhile}%
\algnewcommand{\parState}[1]{\State%
  \parbox[t]{\dimexpr\linewidth-\algmargin}{\strut #1\strut}}

\begin{document}
\begin{algorithm}
  \caption{My pseudo code.}
  \begin{algorithmic}[1]
    \While{this line is sooooooooooo long and boring and too much for algorithmic to handle}
      \State look at this state, this state is just too long for algorithmic to display it properly 
      \While{again this line is sooooooooooo long and boring and too much for algorithmic too handle}
        \State look at this state again, this state is just too long for algorithmic to handle, I'm just going to switch to Word
      \EndWhile
    \EndWhile
    \State
    \parWhile{this line is sooooooooooo long and boring and too much for algorithmic to handle}
      \parState{%
        look at this state, this state is just too long for algorithmic to display it properly}
      \parWhile{again this line is sooooooooooo long and boring and too much for algorithmic too handle}
        \parState{%
          look at this state again, this state is just too long for algorithmic to handle, I'm just going to switch to Word}
      \EndparWhile
    \EndparWhile
  \end{algorithmic}
\end{algorithm}
\end{document}​

在上面的代码中,\parWhile定义\parState您想要的段落样式的伪代码宏。

答案2

\hspace*{5mm}根据您所需的空间使用(5mm根据需要更改)。这很容易,不需要编写宏。对我来说它很好用。

相关内容