I'm trying to do a custom magic square solver using constraint-programming in Python. For this I use python-constraint (http://labix.org/python-constraint).
For this problem the definition of a magic square will be: "A magic square is an arrangement of integers (positives or negatives) in an nxn matrix, and such that the sum of the entries of any row, any column, or any main diagonal is the same."
I have a pre-filled magic square like this:
+----+----+----+----+
| 7 | | | 4 |
+----+----+----+----+
| | | | |
+----+----+----+----+
| 0 | -3 | -2 | 3 |
+----+----+----+----+
| -5 | 6 | | |
+----+----+----+----+
Here is the code I use:
from constraint import *
problem = Problem()
problem.addVariables(range(0, 16), range(-20, 20))
problem.addConstraint(lambda a: a==7, [0])
problem.addConstraint(lambda a: a==4, [3])
problem.addConstraint(lambda a: a==0, [8])
problem.addConstraint(lambda a: a==-3, [9])
problem.addConstraint(lambda a: a==-2, [10])
problem.addConstraint(lambda a: a==3, [11])
problem.addConstraint(lambda a: a==-5, [12])
problem.addConstraint(lambda a: a==6, [13])
problem.addConstraint(ExactSumConstraint(-2), [0,5,10,15])
problem.addConstraint(ExactSumConstraint(-2), [3,6,9,12])
for row in range(4):
problem.addConstraint(ExactSumConstraint(-2),
[row*4+i for i in range(4)])
for col in range(4):
problem.addConstraint(ExactSumConstraint(-2),
[col+4*i for i in range(4)])
solutions = problem.getSolution()
print solutions
I can't find any solutions, while i think my constraints are corrects. The sum of each row and each column and both diagonals must be equal to -2 (based on the row we have on the magic square).
Do you have any ideas ? Thanks.