[Tex/LaTex] How to put an algorithm and a tikz drawing (objects of different type) side-by-side in the same float environment

algorithmscaptionsfloatssubfloats

I am trying to put an algorithm and a tikz' drawing side-by-side inside a figure environment. I am aware of this question but I would like to have a single caption for them. For instance, in the text, Figure 1a would refer to the algorithm while Figure 1b would refer to the tikz' drawing.

Best Answer

I recommend the using of the subcaption package. It works well with caption (same author, thanks Axel).

\documentclass{article}
\usepackage{algorithm}% http://ctan.org/pkg/algorithm
\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx

\usepackage{caption}
\usepackage{subcaption}
\usepackage{tikz}
\begin{document}
\section{foo}
Text

\begin{figure}[!ht]
\begin{subfigure}[b]{.5\linewidth}
\centering
\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}

\caption{Algorithm}\label{fig:alg}
\end{subfigure}%
\begin{subfigure}[b]{.5\linewidth}
\centering
\tikz\draw [fill=red!20] (0,0) rectangle (3,2);
\caption{tikz}\label{fig:tikz}
\end{subfigure}
\caption{Both}\label{fig:both}
\end{figure}

Text \ref{fig:alg} and \ref{fig:tikz} and \ref{fig:both}

\end{document}

enter image description here