5

I'm having trouble indenting a block of pseudocode within an enumeration. Or perhaps more specifically, the algorithm's pseudocode seems to ignore the enumerations indentation. I'm working with the algorithmicx and algpseudocode packages.

\begin{enumerate} 
\item Some text...   
\begin{algorithm}
    \caption{Euclid’s algorithm}\label{euclid}
    \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
    \State $r\gets a\bmod b$
    \While{$r\not=0$}\Comment{We have the answer if r is 0}
    \State $a\gets b$
    \State $b\gets r$
    \State $r\gets a\bmod b$
    \EndWhile\label{euclidendwhile}
    \State \textbf{return} $b$\Comment{The gcd is b}
    \EndProcedure
    \end{algorithmic}
    \end{algorithm}
\end{enumerate}

How can I force the algorithm block to follow the same indentation as the enumeration block?

1 Answer 1

6

You are setting your algorithm inside an algorithm floating environment. And, floats are set (by default) to have full width (\textwidth). It seems like you wish to retain the "floating" structure (ruled) without the floating behaviour (since you're setting it in a list). Then you need to do two things:

  1. Set the float inside a minipage of width \linewidth which adapts to the width of the line inside lists (see Difference between \textwidth, \linewidth and \hsize); and
  2. Due to (1) above, you need to remove the floating behaviour and set it using the [H] float specifier (provided by float which is loaded by algorithm).

Here's the end result in the form of a MWE:

enter image description here

\documentclass{article}
\usepackage{algorithm,algpseudocode}% http://ctan.org/pkg/{algorithms,algorithmicx}
\begin{document}
\begin{enumerate} 
  \item Some text\ldots\par
  \vspace{-\baselineskip}

  \begin{minipage}{\linewidth}
  \begin{algorithm}[H]
    \caption{Euclid’s algorithm}\label{euclid}
    \begin{algorithmic}[1]
      \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
        \State $r\gets a\bmod b$
        \While{$r\not=0$}\Comment{We have the answer if r is 0}
          \State $a\gets b$
          \State $b\gets r$
          \State $r\gets a\bmod b$
        \EndWhile\label{euclidendwhile}
        \State \textbf{return} $b$\Comment{The gcd is b}
      \EndProcedure
    \end{algorithmic}
  \end{algorithm}
  \end{minipage}

  Some more text\ldots
\end{enumerate}
\end{document}
1
  • This worked very well. Thank you for the thorough explanation.
    – Matthew
    Commented Oct 9, 2013 at 5:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .