[Tex/LaTex] How to define a new command in algorithmicx

algorithmicxalgorithmsmacros

The algorithmicx package defines two commands \Require and \Ensure for providing initial conditions. However, I'd like some custom commands such as \Assume, \Define, \Input, etc. At present, I merely rename the above two commands to something I want, like:

\algrenewcommand\algorithmicrequire{\textbf{Input}}

However, this is not really a good solution because

  1. it clutters the algorithm code and what I see in LaTeX is not what is output, which can be confusing if I forget to read the preamble.
  2. it's not useful when the number of custom definitions needed is more than the predefined ones.

How do I define a custom command equivalent to the above two in the algorithmicx package (I'm using algpseudocode)? The examples in the documentation seem to cover blocks like for ... end, etc., and not individual statements.

Best Answer

In the documentation you can find \algnewcommand. In relation \Require is defined as

\algnewcommand\algorithmicrequire{\textbf{Require:}}

So you can do:

\algnewcommand\algorithmicinput{\textbf{INPUT:}}
\algnewcommand\INPUT{\item[\algorithmicinput]}

Here is a complete example:

\documentclass[a4paper,11pt]{article}
\usepackage{algorithmicx}
\usepackage{algorithm}
\usepackage{algpseudocode}
\algnewcommand\algorithmicinput{\textbf{INPUT:}}
\algnewcommand\INPUT{\item[\algorithmicinput]}
\begin{document}
\begin{algorithmic}[1]
\INPUT foo
\Require $x\ge5$
\Ensure $x\le-5$
\Statex
\While{$x>-5$}
\State $x\gets x-1$
\EndWhile
\end{algorithmic}
\end{document}

enter image description here