Text FormattingTwo aligned Columns within Algorithm

Information and discussion about LaTeX's general text formatting features (e.g. bold, italic, enumerations, ...)
Post Reply
cconvey
Posts: 3
Joined: Tue Jul 24, 2012 1:16 am

Two aligned Columns within Algorithm

Post by cconvey »

Any advice for how to pull this off?

I'm writing pseudo code within an "algorithmic" environment. I'd like to have two columns within the algorithm. The left column should the standard constructs such as \STATE, \IF, etc. The right column should have explanatory text.

So I'm looking for something like this as output:

Code: Select all

1: if (x<3)      O(1)
2:    f(x)       O(x^2)
3: else         
4:    g(x)       O(x!)
5: end if
6: y = 2 * x     O(1)


So two kinds of alignment are important: each item in the right-hand column must be vertically aligned with its counterpart on the left, and every entry in the right-hand column should be left-justified along the same (invisible) vertical line.

Is there a clean way to do this in LaTex?

I've tried having "array" or "tabularx" environments inside, or around, the "algorithmic" environment, but that seems to make LaTeX deeply unhappy.

I'm okay with manually calculating what offset the right-hand column should start at relative to something like the page's left margin. But I can't figure out how to implement that kind of alignment. I.e., I can't figure out how to write something like "\hspace{5 in from left margin of page}".

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

cconvey
Posts: 3
Joined: Tue Jul 24, 2012 1:16 am

Re: Two aligned Columns within Algorithm

Post by cconvey »

Clarification: A "clean" solution is nice to have, but one involving messy LaTeX is better than nothing. Worst-case scenario, I can use LaTeX macros or even a LaTeX code generator to cover the mess.
cconvey
Posts: 3
Joined: Tue Jul 24, 2012 1:16 am

Two aligned Columns within Algorithm

Post by cconvey »

I've worked out a solution that I'm reasonably happy with:

Suppose you want the right-hand column of your algorithm to be 2 inches wide. Then you defined the following:

Code: Select all

\newlength{\algrhswidth}
\setlength{\algrhswidth}{2in}
\newcommand{\algrhs}[1]{\hfill \parbox[t]{\algrhswidth}{#1}}
And then, within an algorithmic environment, you can have something like this:

Code: Select all

\STATE $x \leftarrow y$ \algrhs{$O(1)$}
\STATE $y \leftarrow 1$  % don't feel like having a rhs on this one
\STATE $f(x)$ \algrhs{$O(x^2)$}
Post Reply