[Tex/LaTex] Align equal sign in algorithm in vertical line

algorithmshorizontal alignmenttablesvertical alignment

The Code described in [1] produces the following output :

Algorithm Tex Output

For the description of my algorithm I need the equal signs to be perfectly aligned in one vertical line but currently there is still a small but noticeable offset.


[1] TeX-Code :

\usepackage{algorithmicx}
\usepackage{algorithm}

\newcommand{\algrhs}[1]{\hfill \parbox[t]{\algrhswidth}{#1}}

\begin{algorithm} [H]
\begin{algorithmic}[1] 
    \State $A_1 = B_1 + C_1 $ \algrhs{$ A_2 = B_2 - C_2$}
    \State $X_1 = Y_1 + Z_1$ \algrhs{$ X_2 = Y_2 + Z_2$}
\end{algorithmic}
\end{algorithm}

Best Answer

You need to make sure that the equation sides have equal width. That can be achieved by placing the smaller elements inside a box of larger width via \makebox (X_x is wider than A_x and B_x +/- C_x is wider than Y_x +/- Z_x):

enter image description here

\documentclass{article}
\usepackage{algpseudocode}
\usepackage{algorithm,calc}

\newcommand{\mathbox}[3][r]{\makebox[\widthof{$#2$}][#1]{$#3$}}

\begin{document}

\begin{algorithm}[H]
  \begin{algorithmic}[1] 
    \State $\mathbox{X_1}{A_1} = B_1 + C_1$ \hfill $\mathbox{X_2}{A_2} = B_2 - C_2$
    \State $X_1 = \mathbox[l]{B_1 + C_1}{Y_1 + Z_1}$ \hfill
      $X_2 = \mathbox[l]{B_2 - C_2}{Y_2 + Z_2}$
  \end{algorithmic}
\end{algorithm}

\end{document}

In the above example, I've made \mathbox act like \makebox[<width>][<alignment>]{<stuff>} and calc for measuring the width of something via \widthof.

Related Question