The AllDifferent Constraint

Introduces the AllDifferent global constraint in CP-SAT: its syntax, its equivalence to pairwise inequalities, its propagation advantage, and its use in modeling rows, columns, and other 'distinct values' patterns in combinatorial problems.

Step 1 of 157%

Tutorial

The AllDifferent Constraint

The AllDifferent constraint forces a list of integer variables to take pairwise distinct values. In CP-SAT, we add it to a model with

model.AddAllDifferent([x1,x2,,xn]).\texttt{model.AddAllDifferent([}x_1, x_2, \ldots, x_n\texttt{])}.

This single call enforces xixjx_i \neq x_j for every pair of indices iji \neq j.

For example, suppose we declare three integer variables a,b,ca, b, c each with domain {0,1,2}\{0, 1, 2\} and add AddAllDifferent([a,b,c])\texttt{AddAllDifferent([}a, b, c\texttt{])}. Then (a,b,c)(a, b, c) must be a permutation of (0,1,2)(0, 1, 2), giving 3!=63! = 6 feasible assignments:

(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0).(0,1,2),\ (0,2,1),\ (1,0,2),\ (1,2,0),\ (2,0,1),\ (2,1,0).

Note: If the number of variables exceeds the size of the common domain, the constraint is infeasible. Four variables, all with domain {0,1,2}\{0, 1, 2\}, cannot all be distinct — by pigeonhole, at least two must coincide.

navigate · Enter open · Esc close · ⌘K/Ctrl K toggle