-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathconstraint-sudoku.html
203 lines (171 loc) · 6.92 KB
/
constraint-sudoku.html
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
<html>
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<head>
<title>
leontrolski - sudoku constraint solver
</title>
<style>
body {margin: 5% auto; background: #fff7f7; color: #444444; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.8; max-width: 63%;}
@media screen and (max-width: 800px) {body {font-size: 14px; line-height: 1.4; max-width: 90%;}}
pre {width: 100%; border-top: 3px solid gray; border-bottom: 3px solid gray;}
a {border-bottom: 1px solid #444444; color: #444444; text-decoration: none; text-shadow: 0 1px 0 #ffffff; }
a:hover {border-bottom: 0;}
.inline {background: #b3b2b226; padding-left: 0.3em; padding-right: 0.3em; white-space: nowrap;}
blockquote {font-style: italic;color:black;background-color:#f2f2f2;padding:2em;}
details {border-bottom:solid 5px gray;}
</style>
<link href="https://unpkg.com/[email protected]/themes/prism-vs.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.20.0/components/prism-core.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.20.0/plugins/autoloader/prism-autoloader.min.js">
</script>
</head>
<body>
<a href="index.html">
<img src="pic.png" style="height:2em">
⇦
</a>
<p><i>2022-03-01</i></p>
<h1>
Solving sudoku with a constraint solver
</h1>
<p>
Let's solve a sudoku by writing and then using a backtracking constaint solver.
</p>
<p>
The resulting interface we want is:
</p>
<pre class="language-python"><code>solution = next(solutions(game))</code>
</pre>
<p>
Where a game might be:
</p>
<pre class="language-python"><code>game = [
[5, 3, 0, 0, 7, 0, 0, 0, 0],
[6, 0, 0, 1, 9, 5, 0, 0, 0],
[0, 9, 8, 0, 0, 0, 0, 6, 0],
[8, 0, 0, 0, 6, 0, 0, 0, 3],
[4, 0, 0, 8, 0, 3, 0, 0, 1],
[7, 0, 0, 0, 2, 0, 0, 0, 6],
[0, 6, 0, 0, 0, 0, 2, 8, 0],
[0, 0, 0, 4, 1, 9, 0, 0, 5],
[0, 0, 0, 0, 8, 0, 0, 7, 9],
]</code>
</pre>
<p>
And the resulting solution we expect to be:
</p>
<pre class="language-python"><code>expected = [
[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9],
]</code>
</pre>
<p>
Here's the code, we can save this as <code class="inline">sudoku.py</code>
</p>
<pre class="language-python"><code>from functools import partial
from typing import Iterator
from solver import Problem, yield_solutions
Coordinate = tuple[int, int]
Value = int
Game = list[list[Value]]
Assignments = dict[Coordinate, Value]
def all_different(group: list[Coordinate], assignments: Assignments) -> bool:
seen = set()
for v in (assignments[k] for k in group if k in assignments):
if v in seen:
return False
seen.add(v)
return True
rows = [[(i, j) for j in range(9)] for i in range(9)]
cols = [[(i, j) for i in range(9)] for j in range(9)]
boxes = [[(i + k * 3, j + l * 3) for i in range(3) for j in range(3)] for k in range(3) for l in range(3)]
def solutions(game: Game) -> Iterator[Game]:
sudoku = Problem[Coordinate, Value]()
for i in range(9):
for j in range(9):
if game[i][j] > 0:
sudoku.add_variable((i, j), [game[i][j]])
else:
sudoku.add_variable((i, j), [1, 2, 3, 4, 5, 6, 7, 8, 9])
for group in rows + cols + boxes:
for cell in group:
sudoku.add_constraint(cell, partial(all_different, group))
for s in yield_solutions(sudoku):
yield [[s[i, j] for j in range(9)] for i in range(9)]</code>
</pre>
<p>
In summary, we describe the problem as:
</p>
<ul>
<li>
There are 81 coordinates - <code class="inline">(i, j)</code>
. If the coordinate already has a value in <code class="inline">game</code>
, it can only be that value, else it could be any of 1, 2, 3, 4, 5, 6, 7, 8, 9.
</li>
<li>
In each row/column/box, all the values must be different.
</li>
</ul>
<hr>
<p>
What about <code class="inline">solver.py</code>
? Turns out a generic backtracking solver is not crazy crazy complicated:
</p>
<pre class="language-python"><code>from dataclasses import dataclass, field
from json import loads
from typing import Any, Callable, Generic, Hashable, Iterator, TypeVar
K = TypeVar('K', bound=Hashable) # these are "variables"
V = TypeVar('V') # these are "values"
Assignments = dict[K, V]
Constraint = Callable[[Assignments[K, V]], bool]
@dataclass
class KProperties(Generic[K, V]):
domain: list[V]
constraints: list[Constraint[K, V]]
@dataclass
class Problem(Generic[K, V]):
map: dict[K, KProperties[K, V]] = field(default_factory=dict)
def add_variable(self, k: K, domain: list[V]) -> None:
self.map[k] = KProperties(domain=domain, constraints=[])
def add_constraint(self, k: K, constraint: Constraint[K, V]) -> None:
self.map[k].constraints.append(constraint)
def yield_solutions(problem: Problem[K, V]) -> Iterator[Assignments[K, V]]:
q: list[Assignments[K, V]] = [{}]
while q:
assignments = q.pop()
for local in _possible(problem, assignments):
if set(problem.map) - set(local): # if any unassigned
q.append(local)
else:
yield local
def _possible(problem: Problem[K, V], assignments: Assignments[K, V]) -> Iterator[Assignments[K, V]]:
def key(v: K) -> tuple[int, int]:
return -len(problem.map[v].constraints), len(problem.map[v].domain)
unassigned = [k for k in problem.map if k not in assignments]
if not unassigned:
return []
# pick k with the (highest number of constraints, smallest domain)
k = sorted(unassigned, key=key)[0]
for v in problem.map[k].domain:
local = {**assignments, k: v}
if all(constraint(local) for constraint in problem.map[k].constraints):
yield local</code>
</pre>
<p>
</p>
<hr>
<p>
Interestingly, we can generate arbitrary completed sudokus like:
</p>
<pre class="language-python"><code>next(solutions([[0] * 9] * 9))</code>
</pre>
</body>
</html>