-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsudoku_solver.py
81 lines (62 loc) · 2.12 KB
/
sudoku_solver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import re
import numpy as np
import pandas as pd
from pyomo import environ as pyo
from pyomo.dataportal import DataPortal
from pyomo.opt import SolverFactory
import pyutilib.subprocess.GlobalData
pyutilib.subprocess.GlobalData.DEFINE_SIGNAL_HANDLERS_DEFAULT = False
def solve_sudoku(known_cells):
known_cells.columns = ["i", "j", "k"]
# The grid indices and possible values.
N = np.arange(1, 9 + 1)
# Concrete model
model = pyo.ConcreteModel()
# Variable
model.X = pyo.Var(N, N, N, within=pyo.Binary)
# Constraints
model.row_constraint = pyo.ConstraintList()
model.col_constraint = pyo.ConstraintList()
model.block_constraint = pyo.ConstraintList()
model.allcells_constraint = pyo.ConstraintList()
model.knowncells_constraint = pyo.ConstraintList()
# Rows
for i in N:
for k in N:
model.row_constraint.add(sum(model.X[i, j, k] for j in N) == 1)
# Columns
for j in N:
for k in N:
model.col_constraint.add(sum(model.X[i, j, k] for i in N) == 1)
# Blocks
for i in np.arange(1, 9, 3):
for j in np.arange(1, 9, 3):
for k in N:
model.block_constraint.add(
sum(
model.X[p, q, k]
for p in np.arange(i, i + 3)
for q in np.arange(j, j + 3)
)
== 1
)
# All cells
for i in N:
for j in N:
model.allcells_constraint.add(sum(model.X[i, j, k] for k in N) == 1)
# Known cells
for i, j, k in zip(known_cells["i"], known_cells["j"], known_cells["k"]):
# if k != 0:
model.knowncells_constraint.add(model.X[i, j, k] == 1)
# Objective (none)
model.objective = pyo.Objective(expr=1)
# Solving
opt = SolverFactory("glpk")
solution = opt.solve(model)
res = np.zeros((9, 9))
for v in model.component_data_objects(pyo.Var, active=True):
val = v.value
if val > 0:
i, j, k = [int(x) for x in re.findall("[0-9]", v.name)]
res[i - 1, j - 1] = k
return res