[Tex/LaTex] Use algorithm2e inside tcolorbox

algorithm2etcolorbox

I use the algorithm2e package to typeset algorithms. Now I would like to put a tcolorbox around an algorithm. My first approach looked like this:

\begin{tcolorbox}
    \begin{algorithm}
        $a \leftarrow 1$
        \caption{My Algorithm}
    \end{algorithm}
\end{tcolorbox}

This yields the following error: LaTeX Error: Not in outer par mode. My understanding is that this happens because both the tcolorbox and the algorithm are floating environments that cannot be nested.

There is already a similar question: How to put \algorithm and \algorithmic environments inside a box? The accepted answer there does not work for me, because it simply describes how to put an arbitrary box around the algorithm. I also tried to use \RestyleAlgo{tcolorbox}, but to no avail. I am looking for a method that specifically uses a tcolorbox.

As a final remark, I do not need to typeset the algorithms particularly with algorithm2e, any other algorithm package will do as well.

Best Answer

The error "Not in outer par mode" is because the algorithm environment wants to float, yet it's contained inside a non-floating tcolorbox. The only way to make algorithm2e not floats its algorithms is to use the [H] float specifier:

enter image description here

\documentclass{article}
\usepackage[paper size={15cm,10cm}]{geometry}
\usepackage[most]{tcolorbox}
\usepackage{algorithm2e}

\begin{document}

\begin{tcolorbox}
  \begin{algorithm}[H]
    $a \leftarrow 1$
    \caption{My Algorithm}
  \end{algorithm}
\end{tcolorbox}
\end{document}
Related Question