I've always found the simplest way to do loops of this sort is the /foreach
construct in PGF (\usepackage{pgffor}
). The simplest way to use it would be something like:
\foreach \i/\j in {1/2, 1/3, 2/39} {$x_{\i} + x_{\j} \ge 1$ \quad}
which would just put everything on one line with \quad
s between them.
If you want to format this, you might want to line up the greater-thans, e.g. in an align environment. Unfortunately, just doing a \foreach
loop in an align breaks as it can't handle the \\
line breaks properly. Instead, we can use a \foreach
loop to build up a macro, and then afterwards wrap that macro in the align environment. Below (example 2) I use \xappto
from the etoolbox package to build up the \constraintlist
macro in this way.
By building things up in a macro, we can get quite creative. In example 3, I'm using the pgfmath
library to only add \\
to the macro after every third constraint (otherwise &
is added), which gives us the constraints in three columns, all nicely aligned on the greater-than sign.
Here's the code:
\documentclass{article}
\usepackage{pgffor} % \foreach
\usepackage{amsmath} % align* environment
\usepackage{etoolbox} % \xappto and \gappto
\usepackage{pgfmath} % \pgfmathparse and \pgfmathresult
\begin{document}
Example 1:
\begin{center}
\foreach \i/\j in {
1/2,
1/3,
2/39,
2019/2020
}{$x_{\i} + x_{\j} \ge 1$ \\}
\end{center}
Example 2:
\def\constraintlist{}
\foreach \i/\j in {1/2, 1/3, 2/39, 2019/2020}{
\xappto\constraintlist{x_{\i} + x_{\j} &\ge 1 \noexpand\\}
}
\begin{align*}
\constraintlist
\end{align*}
Example 3:
\def\constraintlist{}
\foreach \i/\j [count = \index] in {1/2, 1/3, 2/39, 2019/2020, a/b, foo/bar}{
\xappto\constraintlist{x_{\i} + x_{\j} &\ge 1}
\pgfmathparse{mod(\index, 3)==0}
\ifnum\pgfmathresult=1
\gappto\constraintlist{\\}
\else
\gappto\constraintlist{&}
\fi
}
\begin{align*}
\constraintlist
\end{align*}
\end{document}
which renders:
