[PYTHON] Combine Sudoku and solve optimally

Solve Sudoku

Sudoku can be easily solved by using Combinatorial optimization.

"Sudoku" is a registered trademark of Nikoli Source Nikoli http://www.nikoli.co.jp/ja/

Formulation

$ \ mbox {variables} $ $ x_ {ijk} \ in \ {0, 1 \} ~ \ forall i, j, k $ Is the square i, j the number k + 1? (1)
$ \ mbox {subject to} $ $ \ sum_k {x_ {ijk}} = 1 ~ \ forall i, j $ One number (2)
$ \ sum_k {x_ {ikj}} = 1 ~ \ forall i, j $ No vertical same number (3)
$ \ sum_k {x_ {kij}} = 1 ~ \ forall i, j $ There is no same number next to it (4)
$ 3 \ times The same applies to 3 $ cells (5)
Specify numbers (6)

Solve with Python

[pulp](http://qiita.com/Tsutomu-KKE@github/items/bfbf4c185ed7004b5721#%E3%82%BD%E3%83%95%E3%83%88%E3%81%AE%E3%82 Use% A4% E3% 83% B3% E3% 82% B9% E3% 83% 88% E3% 83% BC% E3% 83% AB) and pandas.

The problem is that it's in a string.

python


prob = """\
..6.....1
.7..6..5.
8..1.32..
..5.4.8..
.4.7.2.9.
..8.1.7..
..12.5..3
.6..7..8.
2.....4..
"""

Let's formulate and solve it.

python


import pandas as pd, numpy as np
from more_itertools import grouper
from pulp import *
r = range(9)

m = LpProblem() #Mathematical model
a = pd.DataFrame([(i, j, k, LpVariable('x%d%d%d'%(i,j,k), cat=LpBinary))
                  for i in r for j in r for k in r],
                 columns=['Vertical', 'side', 'number', 'x']) # (Formulation 1)
for i in r:
    for j in r:
        m += lpSum(a[(a.Vertical== i) & (a.side== j)].x) == 1 # (Formulation 2)
        m += lpSum(a[(a.Vertical== i) & (a.number== j)].x) == 1 # (Formulation 3)
        m += lpSum(a[(a.side== i) & (a.number== j)].x) == 1 # (Formulation 4)
for i in range(0, 9, 3):
    for j in range(0, 9, 3):
        for k in r:
            m += lpSum(a[(a.Vertical>= i) & (a.Vertical< i+3) & # (Formulation 5)
                         (a.side>= j) & (a.side< j+3) & (a.number== k)].x) == 1
for i, s in enumerate(prob.split('\n')):
    for j, c in enumerate(s):
        if c.isdigit():
            k = int(c)-1 # (Formulation 6)
            m += lpSum(a[(a.Vertical== i) & (a.side== j) & (a.number== k)].x) == 1
m.solve() #Solved with solver
f = a.x.apply(lambda v: value(v) == 1) #Selected numbers
print(np.array(list(grouper(9, a.number[f] + 1))))
>>>
[[5 3 6 8 2 7 9 4 1]
 [1 7 2 9 6 4 3 5 8]
 [8 9 4 1 5 3 2 6 7]
 [7 1 5 3 4 9 8 2 6]
 [6 4 3 7 8 2 1 9 5]
 [9 2 8 5 1 6 7 3 4]
 [4 8 1 2 9 5 6 7 3]
 [3 6 9 4 7 1 5 8 2]
 [2 5 7 6 3 8 4 1 9]]

Docker Other puzzles can also be found at tsutomu7 / puzzle. Look at the host address in your browser by doing the following:

docker run -d -p 80:8888 tsutomu7/puzzle

reference

-Learn Combinatorial Optimization Through Sudoku -Use combinatorial optimization -Solving puzzles by mathematical optimization -Python in optimization -Puzzle Combinatorial Optimization Technique -Sudoku in Python

that's all