This example shows a smart representation of a matrix and a concomitant defined constraint of higher order. The model will eliminate symmetries by imposing order constraints. Propagation will be drastically improved by exploiting a redundant constraint.

Figure 7.3 shows a script realizing the model and distribution strategy just discussed. The actual script is created by a procedure MagicSquare taking N as parameter.

The script represents the matrix as a tuple with elements. The tuple is the value of the root variable Square. The function

{Field I J}

returns the component of Square that represents the field at position (I,J). The variable Sum takes the sum of the rows, columns, and main diagonals as value. The procedure

{Assert F}

takes a function F and posts the constraint

{F 1} + {F 2} +...+ {F N} = Sum

Obviously, {Assert F} is a defined constraint of higher order. With the help of this defined constraint it is straightforward to state that the sums of the rows, columns, and main diagonals are all equal to Sum.

With the Explorer you can find out that for N=3 there is exactly one magic square satisfying the ordering constraints of our model. Without the ordering constraints there are 8 different solutions. Omitting the propagator for the redundant constraint will increase the search tree by an order of magnitude.