[Tex/LaTex] Boxed algorithm with caption at top

algorithmscaptionsframedpositioning

I wish to obtain a boxed algorithm with the caption at the top. I also need to control the caption format, and the heading.

I tried using the algorithm package:

%algorithms
\usepackage[boxed]{algorithm}
\usepackage{algorithmicx,algpseudocode}

% Change float style of algorithm from "ruled" to "plaintop"
\floatstyle{plaintop}
\restylefloat{algorithm}

% Change caption format
\captionsetup[algorithm]{font=scriptsize,labelformat=bf-gara,justification=raggedright,singlelinecheck=false,name=Algorithm}

% Change caption heading
\renewcommand{\thealgorithm}{A.\arabic{algorithm}}

which however does not draw the box around the algorithm. I could require all floats to be boxed, but this would affect figures and tables too, which I do not want to be boxed.

Alternatively, I could use the algorithm2e package , which offers more control over caption position, but then I get into troubles when I need to specify caption format and heading:

\thealgorithm undefined. \renewcommand{\thealgorithm}
Argument of \ALG@cmd@2@algorithmiccomment has an extra }. \While{$r\not=0$}\Comment{

How can I save both ways? Thanks!

Best Answer

Write yourself a new style based on the old boxed style:

enter image description here

\documentclass{article}

\usepackage{algorithm,algpseudocode,caption}

% Define a new boxedtopcap float style
\makeatletter
\newcommand\fs@boxedtopcap{\def\@fs@cfont{\bfseries}\let\@fs@capt\floatc@plain
  \def\@fs@pre{\setbox\@currbox\vbox{\hbadness10000
    \moveleft3.4pt\vbox{\advance\hsize by6.8pt
      \hrule \hbox to\hsize{\vrule\kern3pt
        \vbox{\kern3pt\box\@currbox\kern3pt}\kern3pt\vrule}\hrule}}}%
  \def\@fs@mid{\kern2pt}%
  \def\@fs@post{}\let\@fs@iftopcapt\iftrue}
\makeatother

% Change float style of algorithm from "ruled" to "plaintop"
\floatstyle{boxedtopcap}
\restylefloat{algorithm}

% Change caption format
\captionsetup[algorithm]{
  justification = raggedright,
  singlelinecheck = false,
  name = Algorithm
}

% Change caption heading
\renewcommand{\thealgorithm}{A.\arabic{algorithm}}

\begin{document}

\begin{algorithm}
  \caption{Euclid's algorithm}
  \begin{algorithmic}[1]
    \Procedure{Euclid}{$a,b$}\Comment{The g.c.d.\ of $a$ and $b$}
      \State $r \gets a \bmod b$
      \While{$r \neq 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
      \State \textbf{return} $b$\Comment{The g.c.d.\ is $b$}
    \EndProcedure
  \end{algorithmic}
\end{algorithm}

\end{document}