I'm trying to solve a Sudoku with cvxpy
optimization package.
I'm really new to both optimization and cvxpy.
The constraints are:
- all the values are between 1 to 9
- sum of all rows = 45
- sum of all columns = 45
- sum of all squares = 45
- the given numbers (I'm trying to solve a 17-clues Sudoku).
So, here is my code:
from cvxpy import *
import numpy as np
x = Variable((9, 9), integer=True)
obj = Minimize(sum(x)) #whatever, if the constrains are fulfilled it will be fine
const = [x >= 1, #all values should be >= 1
x <= 9, #all values should be <= 9
sum(x, axis=0) == 45, # sum of all rows should be 45
sum(x, axis=1) == 45, # sum of all cols should be 45
sum(x[0:3, 0:3]) == 45, sum(x[0:3, 3:6]) == 45, #sum of all squares should be 45
sum(x[0:3, 6:9]) == 45,
sum(x[3:6, 0:3]) == 45, sum(x[3:6, 3:6]) == 45,
sum(x[3:6, 6:9]) == 45,
sum(x[6:9, 0:3]) == 45, sum(x[6:9, 3:6]) == 45,
sum(x[6:9, 6:9]) == 45,
x[0, 7] == 7, #the values themselves
x[0, 8] == 1,
x[1, 1] == 6,
x[1, 4] == 3,
x[2, 4] == 2,
x[3, 0] == 7,
x[3, 4] == 6,
x[3, 6] == 3,
x[4, 0] == 4,
x[4, 6] == 2,
x[5, 0] == 1,
x[5, 3] == 4,
x[6, 3] == 7,
x[6, 5] == 5,
x[6, 7] == 8,
x[7, 1] == 2,
x[8, 3] == 1]
prob = Problem(objective=obj, constraints=const)
prob.solve()
What I get from cvxpy is
prob.status
Out[2]: 'infeasible_inaccurate'
This is for sure a valid Sudoku, and I checked the numbers million times.
Why am I not getting the answer?
Any help would be appreciated!