4

I would like the algorithm (in ruled style) appear below the rules, in the center and without a rule below itself.

this is what I have so far non-centered caption with rule below

with the following code:

\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{algorithmic}
\usepackage[linesnumbered,ruled]{algorithm2e}

\makeatletter
\newenvironment{Ualgorithm}[1][htpb]{\def\@algocf@post@ruled{\kern\interspacealgoruled\hrule  height\algoheightrule\kern3pt\relax}%
\def\@algocf@capt@ruled{under}
\begin{algorithm}[#1]}
{\end{algorithm}}
\makeatother

\begin{document}

\begin{Ualgorithm}[H]
\SetAlgoLined
\KwData{this text}
\KwResult{Write here the result }
initialization\;
\While{While condition}{
    instructions\;
\eIf{condition}{
    instructions1\;
    instructions2\;
}{
instructions3\;
}
}
\caption{How to write algorithms}
\end{Ualgorithm}

\end{document}

and this is about what I would like to have centered caption with no rule below

plus I would like to have the whole space between the rules colored (with the same color every time).

Is there a way to do these changes to the code? Thanks for your suggestions.

4

To remove the last line you can use:

\setlength\algotitleheightrule{0pt}

while to center the caption:

\SetAlgoCaptionLayout{centerline}

In other words, your custom Ualgorithm environment can be rewritten as:

\newenvironment{Ualgorithm}[1][htpb]{\def\@algocf@post@ruled{\kern\interspacealgoruled\hrule  height\algoheightrule\kern3pt\relax}%
\def\@algocf@capt@ruled{under}%
\setlength\algotitleheightrule{0pt}%
\SetAlgoCaptionLayout{centerline}%
\begin{algorithm}[#1]}
{\end{algorithm}}

Complete MWE:

\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{algorithmic}
\usepackage[linesnumbered,ruled]{algorithm2e}

\makeatletter
\newenvironment{Ualgorithm}[1][htpb]{\def\@algocf@post@ruled{\kern\interspacealgoruled\hrule  height\algoheightrule\kern3pt\relax}%
\def\@algocf@capt@ruled{under}%
\setlength\algotitleheightrule{0pt}%
\SetAlgoCaptionLayout{centerline}%
\begin{algorithm}[#1]}
{\end{algorithm}}
\makeatother

\begin{document}

\begin{Ualgorithm}[H]
\SetAlgoLined
\KwData{this text}
\KwResult{Write here the result }
initialization\;
\While{While condition}{
    instructions\;
\eIf{condition}{
    instructions1\;
    instructions2\;
}{
instructions3\;
}
}
\caption{How to write algorithms}
\end{Ualgorithm}

\end{document} 

enter image description here

| improve this answer | |
  • Thank you! Would you also know how to make the colored background? – Elza May 14 '17 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.