A Walkthrough Leading to the Ability to Write Algorithms in LaTeX

Introduction and Context

Summary of aims

Below is an explanation of how one would go about installing the necessary packages to be able to write algorithms using LaTeX and the algorithmicx and algorithm packages.

In it, I detail a workflow for downloading files from CTAN, unzipping them, finding your LaTeX directory path, copying files to that path, and refreshing the LaTeX environment.

I also give a recommendation as to what text editor to use with which packages (SublimeText3 and LaTeXTools). This recommendation is meant to be a suggestion for those who do not know where to start, not a recommendation that competes with any entrenched text editors.

Context and Caveats

This post is an extract and expansion of an answer I posted to StackExchange on which of the different algorithm formatting environments environments are more or less useful in different cases.

Admittedly, I do not know which would be better or worse for different purposes, nor do I know which ones will and won’t cause conflicts with other packages.

Furthermore, I do not know how to use these packages in all of their glory yet. I may post something further when I have achieved that knowledge.

However, I do know that some of the steps that were included in the original answer by Konrad Rudolph would be opaque to some less well-seasoned (aka aspiring) TeXnicians.

I try to explain how to deal with packages that do not come installed in basic LaTeX build provided by MacTex for OS X users. I do not know how to help out those who are not running a recent version of OS X. To this end, I include a brief discussion of the TeX distribution’s path, how to find it, and how to add a package to it in case you don’t already know how.

SublimeText 3 + LaTexTools: A good TeX editor

Though there are many workflows for using LaTeX, my current is my favorite and involves a couple of steps that I think could benefit others.

Firstly, my text editor for many purposes is SublimeText 3, which on its own is fine, but once enabled with Package Control is a remarkable force to be reckoned with. Package Control is SublimeText’s package manager that makes souping up SublimeText much easier and enables all sorts of crazy abilities.

The installation of Sublime Text 3 can be found at their website, and you can install Package Control by following the instructions at the Package Control website.

Then once you have Package Control installed, download the LaTeXTools package, which has some pretty amazing abilities. The amount of things that LaTeXTools can do for you is astounding and unable to be explained without overshadowing the rest of the post.

I will just say the one piece that is left out of the LaTeXTools initial how-to guide, which is that:

In order to compile a LaTeX document in SublimeText3 on OS X with LaTexTools installed is to click ⌘+B.

Now we’ll get on to setting up the algorithm typesetting environment you came here for.

Setting up Algorithmicx

First, you will need to install algorithmicx in your the path that your TeX distribution can read.

Kieran Healy’s accidental introduction to the TeX distribution path during his walkthrough for installing Minion Pro[1]

A good way to learn whether about the TeX distribution’s paths covers a set of files is to walk through this tutorial by @kieran Healy, which describes the steps needed to make a font available to TeX, which is a much more arduous process (since you need to deal with font metric files, and have the license to the font in question, among other things).

Most importantly for our purposes here is the command

kpsexpand '$TEXMFLOCAL'

Which should print the local directory in your distribution’s path to the console, if it doesn’t work, try

DEST=`kpsexpand '$TEXMFLOCAL'`&& echo $DEST

And if that doesn’t work, I’d suggest reinstalling TeXLive if you are on OS X and I have no clue what to do if you aren’t.

Downloading Algorithmicx

Then, once you’ve identified your distribution’s path download the relevant CTAN files from this website, which will download a zip file, which you will need to unzip. If you have any issues unzipping the file, please leave a comment and I will try to address your concern.

Moving the Algorithmicx folder to be available to your global TeX filepath

You will want to move these files into the directory of that your TeX distribution can see.

What I would suggest doing is attempting to navigate through the finder to find the folder in question, however, if you are in a hurry, you can try to use the following:

  1. Open a terminal window (using ⌘+␣ [1] and typing Terminal).
  2. Insert the following text
    DEST=kpsexpand '$TEXMFLOCAL'
  3. Navigate to the unzipped file (it will likely be in your ~/Downloads folder with the name algorithmicx).
    1. Ignore the following lines if you know how to navigate between files in the Terminal.
    2. If you do not know how to navigate between files in the Terminal I recommend the tutorial/course Learning the Command Line the Hard Way.
    3. In brief I recommend using ls to identify which files are available in the current directory (which you can identify by typing pwd) and cd which when followed by a space and directory name (such as that listed by ls will move into that directly.
      1. cd ~ will take you to your home directory.
    4. If you have just opened the terminal, and your file was downloaded and unzipped to the Downloads folder, then cd ~/Downloads will take you to the appropriate directory.

The following line assumes that you downloaded and unzipped the algorithmicx folder into a Downloads folder which is directly beneath your home directory. Please change the commands if that does not hold for you. We are going to use the command cp -r [1] [1] or sudo scp -r [1] [1] which copies or securely copies files rescursively from the first argument to the location of the second argument. The sudo [3] and secure copy (scp) is necessary if you do not have the permissions to complete that copy, which is likely given the usual place where the TeX distribution files are installed.

  1. Type into the terminal cp -r ~/Downloads/algorithmicx $DEST.
  2. If that returns an error citing that you don’t have the appropriate permissions(only do this if you are confident with what you are doing), type instead sudo scp -r ~/Downloads/algorithmicx $DEST and type in your password when you are prompted. If you have any reason to believe that the algorithmicx package is not safe or to be trusted (e.g., if you downloaded from somewhere other than CTAN or if you are for some reason wary of CTAN) do not use sudo to move these files.
  3. In the terminal, run texconfig rehash.

Now you should be ready to test out these packages.

Testing the Algorithm and Algorithmicx environments

Now that we have the algorithmicx installed, and algorithm is already isntalled, we can create a TeX document that we then compile and look at the output.

In a directory that you work with regularly, create a new document in your TeX Editor. And paste the following text(or download it here):

\documentclass{article} %  
% \usepackage{nips15submit_e,mathtools, graphicx,amsmath,amsthm, amssymb,epstopdf,verbatim,array,booktabs,mathtools}  
% \usepackage{tikz}


\usepackage{algpseudocode,algorithm,algorithmicx}  
\newcommand*\DNA{\textsc{dna}}

\newcommand*\Let[6]{\State #1 $\gets$ #2}  
\algrenewcommand\algorithmicrequire{\textbf{Precondition:}}  
\algrenewcommand\algorithmicensure{\textbf{Postcondition:}}

\begin{document}

\begin{algorithm}  
  \caption{Counting mismatches between two packed \DNA strings  
    \label{alg:packed-dna-hamming}}  
  \begin{algorithmic}[5]  
    \Require{$x$ and $y$ are packed \DNA strings of equal length $n$}  
    \Statex  
    \Function{Distance}{$x, y$}  
      \Let{$z$}{$x \oplus y$} \Comment{$\oplus$: bitwise exclusive-or}  
      \Let{$\delta$}{$0$}  
      \For{$i \gets 1 \textrm{ to } n$}  
        \If{$z_i \neq 0$}  
          \Let{$\delta$}{$\delta + 1$}  
        \EndIf  
      \EndFor  
      \State \Return{$\delta$}  
    \EndFunction  
  \end{algorithmic}  
\end{algorithm}

\end{document}

Once you run compile this document (if using SublimeText 3 and LaTeXTools this should consist of hitting ⌘+B) it should produce a pdf that looks like the following image:

Basic Algorithm
Figure 1: An example of an algorithm typset in LaTeX using the algorithmicx and algorithm packages.

If you see something that looks like the above image — Congratulations! You just typeset an algorithm using LaTeX and the algorithmicx and algorithm packages! Good job!

Some Parting Notes

In general, you should embed the algorithmic environment inside the algorithm environment. This has the effect of treating the entire algorithmic environment as a single “floating” entity. If you do not do this, there is a chance that the environment, which consists of a box for each element may be split across multiple pages.

This example differs from the original that Konrad posted, as the nice sans-serif numbers and fontspec are unnecessary parts for someone just interested in getting algorithms to render properly.

Additionally, note that we included all of the following packages with this line of TeX:

\usepackage{algpseudocode,algorithm,algorithmicx}

I must confess I do not fully understand the differences between these packages(algpseudocode,algorithm,algorithmicx) — but I do know that algpseudocode code is contained within algorithmicx. Someday, I’ll return to this an try to explain why they’re different, but that task will have to prove important enough to be worth my and your time reading. If anyone has any comments along these lines please post them below and I will attempt to respond to them in a timely matter[4].

Happy coding!


  1. NB: Installing Minion pro is not going to be explained in the course of my explanation. Healy’s epxlanation of how to do that is much more thorough than mine.  ↩

  2. The symbol ␣ is designates the space bar being pressed.  ↩

  3. sudo refers to the ability for you as the super-user of the computer to do whatever you wish. The exact etymology/lexical meaning of the sudo abbreviation is fairly fraught, so just take this to be a rough explanation of its purpose not the actual meaning of the term.  ↩

  4. This all was prompted by my need to typeset some work I plan on submitting to the upcoming NIPS conference, which I will be working on in the coming weeks. I apologize if that delays my response. If you are in the same boat as I — I wish us both the best of luck and tonnes of great typsetting :).  ↩