I'm solving the magic square problem for my operational research exam.
The constraints of my model are that the sum of the elements on the lines must be equal to a constant (var constant), that the sum of the elements on the columns must be equal to the same constant and that also the sum on the diagonals must be equal to the same constant . These constraints are r, c, d1
and d2
.
I have also inserted a constraint q1
to find this constant because there is the property that multiplying the order of the matrix by the magic constant yields the sum of the values from 1 to k^2
.
For k=3
, I get this matrix in output:
1 9 5
5 9 1
5 1 9
Magic_Constant: 15
But that's not good, I have to find a way to insert a constraint that says that all the values in the matrix must be different (from 1
to n^2
). But I can't use the alldiff
operator!
How can I do?
### PARAMETER ###
param k;
param firstKnumber = ((k*k)/2)*(k*k+1);
### VARIABLE ###
var x{1..k,1..k} >= 1 <= k*k integer;
var constant;
### CONSTRAINT ###
subject to r{t in 1..k}: sum{i in 1..k} x[t,i] = constant;
subject to c{t in 1..k}: sum{i in 1..k} x[i,t] = constant;
subject to d1: sum{i in 1..k} x[i,i] = constant;
subject to d2: sum{i in 1..k} x[i,k-i+1] = constant;
subject to q1: firstKnumber = constant*k;
### OBJECTIVE ###
minimize Magic_Constant: constant;
data;
param k:= 3;
option solver gurobi;
solve;
display Magic_Constant;
for{i in 1..n} {
for {j in 1..n} {
printf "%3d ", x[i,j];
}
printf "\n";
}