Solve your model

Resolution in the Cloud

Following the definition of the Sudoku model, the final step simply consists in submitting this model to the Qaekwy Cloud Instance for resolution, and displaying the computed solution.

Solving the Model

With the variables defined and constraints registered, the model is fully assembled. To find the solution, simply call solve_one():

# Solve the model and retrieve the first valid solution found
s = m.solve_one()

# Display the result
s.pretty_print()

Solution

----------------------------------------
Solution:
----------------------------------------
grid: (9 x 9 matrix)
    1 7 8 3 2 5 6 9 4
    5 4 3 6 1 9 8 2 7
    6 9 2 7 4 8 3 5 1
    2 6 5 4 8 1 7 3 9
    4 8 1 9 7 3 2 6 5
    9 3 7 2 5 6 1 4 8
    7 5 9 8 3 2 4 1 6
    3 1 4 5 6 7 9 8 2
    8 2 6 1 9 4 5 7 3
----------------------------------------

Conclusion

Qaekwy facilitates the model-then-solve approach by decoupling model in two parts (defining the variables, defining the constraints) before to simply submitting it to the solver instance. In other words, modelling means describing how the problem looks like, and it is the solver’s task to find the suitable solution.

Complete code

import qaekwy as qw

my_problem = [
    [0, 7, 0,  0, 0, 0,  6, 9, 0],
    [0, 0, 0,  6, 1, 0,  0, 0, 0],
    [0, 9, 2,  0, 0, 0,  0, 5, 0],

    [0, 0, 0,  0, 8, 1,  7, 0, 9],
    [4, 0, 0,  0, 0, 3,  0, 0, 0],
    [0, 0, 0,  0, 5, 6,  1, 0, 8],

    [0, 5, 9,  0, 0, 0,  0, 1, 0],
    [0, 0, 0,  5, 6, 0,  0, 0, 0],
    [0, 2, 0,  0, 0, 0,  5, 7, 0]
]

m = qw.Model()

grid = m.integer_matrix("grid", rows=9, cols=9, domain=(1, 9))

for i in range(9):
    m.constraint_distinct(grid.row(i))
    m.constraint_distinct(grid.col(i))

for i in range(0, 9, 3):
    for j in range(0, 9, 3):
        m.constraint_distinct(grid.slice(i, j,i + 3, j + 3))

for i in range(9):
    for j in range(9):
        if my_problem[i][j] != 0:
            m.constraint(grid[i][j] == my_problem[i][j])

s = m.solve_one()
s.pretty_print()