This repository has been archived by the owner on May 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 147
/
sudoku-txt.py
executable file
·333 lines (306 loc) · 10.1 KB
/
sudoku-txt.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
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#!/usr/bin/python
#
# Sudoku Generator and Solver in 250 lines of python
# Copyright (c) 2006 David Bau. All rights reserved.
#
# Can be used as either a command-line tool or as a cgi script.
#
# As a cgi-script, generates puzzles and estimates their level of
# difficulty. Uses files sudoku-template.pdf/.ps/.txt/.html
# in which it can fill in 81 underscores with digits for a puzzle.
# The suffix of the request URL determines which template is used.
#
# On a command line without any arguments, prints text for a
# random sudoku puzzle, with an estimate of its difficulty.
# On a command line with a filename, solves the given puzzles
# (files should look like the text generated by the generator).
#
# Adapted for Adafruit_Thermal library by Phil Burgess for
# Adafruit Industries.
from __future__ import print_function
import sys, os, random, getopt, re
from Adafruit_Thermal import *
printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
def main():
printer.setLineHeight(24) # So graphical chars fit together
args = sys.argv[1:]
if len(args) > 0:
puzzles = [loadboard(filename) for filename in args]
else:
puzzles = [makepuzzle(solution([None] * 81))]
for puzzle in puzzles:
printer.println("PUZZLE:")
printer.feed(1)
printer.print(printboard(puzzle))
printer.feed(1)
printer.println("RATING:", ratepuzzle(puzzle, 4))
if len(args) > 0:
printer.println()
printer.println("SOLUTION:")
answer = solution(puzzle)
if answer is None: printer.println("NO SOLUTION")
else: printer.print(printboard(answer))
printer.feed(3)
def makepuzzle(board):
puzzle = []; deduced = [None] * 81
order = random.sample(xrange(81), 81)
for pos in order:
if deduced[pos] is None:
puzzle.append((pos, board[pos]))
deduced[pos] = board[pos]
deduce(deduced)
random.shuffle(puzzle)
for i in xrange(len(puzzle) - 1, -1, -1):
e = puzzle[i]; del puzzle[i]
rating = checkpuzzle(boardforentries(puzzle), board)
if rating == -1: puzzle.append(e)
return boardforentries(puzzle)
def ratepuzzle(puzzle, samples):
total = 0
for i in xrange(samples):
state, answer = solveboard(puzzle)
if answer is None: return -1
total += len(state)
return float(total) / samples
def checkpuzzle(puzzle, board = None):
state, answer = solveboard(puzzle)
if answer is None: return -1
if board is not None and not boardmatches(board, answer): return -1
difficulty = len(state)
state, second = solvenext(state)
if second is not None: return -1
return difficulty
def solution(board):
return solveboard(board)[1]
def solveboard(original):
board = list(original)
guesses = deduce(board)
if guesses is None: return ([], board)
track = [(guesses, 0, board)]
return solvenext(track)
def solvenext(remembered):
while len(remembered) > 0:
guesses, c, board = remembered.pop()
if c >= len(guesses): continue
remembered.append((guesses, c + 1, board))
workspace = list(board)
pos, n = guesses[c]
workspace[pos] = n
guesses = deduce(workspace)
if guesses is None: return (remembered, workspace)
remembered.append((guesses, 0, workspace))
return ([], None)
def deduce(board):
while True:
stuck, guess, count = True, None, 0
# fill in any spots determined by direct conflicts
allowed, needed = figurebits(board)
for pos in xrange(81):
if None == board[pos]:
numbers = listbits(allowed[pos])
if len(numbers) == 0: return []
elif len(numbers) == 1: board[pos] = numbers[0]; stuck = False
elif stuck:
guess, count = pickbetter(guess, count, [(pos, n) for n in numbers])
if not stuck: allowed, needed = figurebits(board)
# fill in any spots determined by elimination of other locations
for axis in xrange(3):
for x in xrange(9):
numbers = listbits(needed[axis * 9 + x])
for n in numbers:
bit = 1 << n
spots = []
for y in xrange(9):
pos = posfor(x, y, axis)
if allowed[pos] & bit: spots.append(pos)
if len(spots) == 0: return []
elif len(spots) == 1: board[spots[0]] = n; stuck = False
elif stuck:
guess, count = pickbetter(guess, count, [(pos, n) for pos in spots])
if stuck:
if guess is not None: random.shuffle(guess)
return guess
def figurebits(board):
allowed, needed = [e is None and 511 or 0 for e in board], []
for axis in xrange(3):
for x in xrange(9):
bits = axismissing(board, x, axis)
needed.append(bits)
for y in xrange(9):
allowed[posfor(x, y, axis)] &= bits
return allowed, needed
def posfor(x, y, axis = 0):
if axis == 0: return x * 9 + y
elif axis == 1: return y * 9 + x
else: return ((0,3,6,27,30,33,54,57,60)[x] + (0,1,2,9,10,11,18,19,20)[y])
def axisfor(pos, axis):
if axis == 0: return pos / 9
elif axis == 1: return pos % 9
else: return (pos / 27) * 3 + (pos / 3) % 3
def axismissing(board, x, axis):
bits = 0
for y in xrange(9):
e = board[posfor(x, y, axis)]
if e is not None: bits |= 1 << e
return 511 ^ bits
def listbits(bits):
return [y for y in xrange(9) if 0 != bits & 1 << y]
def allowed(board, pos):
bits = 511
for axis in xrange(3):
x = axisfor(pos, axis)
bits &= axismissing(board, x, axis)
return bits
def pickbetter(b, c, t):
if b is None or len(t) < len(b): return (t, 1)
if len(t) > len(b): return (b, c)
if random.randint(0, c) == 0: return (t, c + 1)
else: return (b, c + 1)
def entriesforboard(board):
return [(pos, board[pos]) for pos in xrange(81) if board[pos] is not None]
def boardforentries(entries):
board = [None] * 81
for pos, n in entries: board[pos] = n
return board
def boardmatches(b1, b2):
for i in xrange(81):
if b1[i] != b2[i]: return False
return True
def printboard(board):
# Top edge of board:
out = (' '
+ chr(0xC9) # Top left corner
+ chr(0xCD) # Top edge
+ chr(0xD1) # Top 'T'
+ chr(0xCD) # Top edge
+ chr(0xD1) # Top 'T'
+ chr(0xCD) # Top edge
+ chr(0xCB) # Top 'T' (double)
+ chr(0xCD) # Top edge
+ chr(0xD1) # Top 'T'
+ chr(0xCD) # Top edge
+ chr(0xD1) # Top 'T'
+ chr(0xCD) # Top edge
+ chr(0xCB) # Top 'T' (double)
+ chr(0xCD) # Top edge
+ chr(0xD1) # Top 'T'
+ chr(0xCD) # Top edge
+ chr(0xD1) # Top 'T'
+ chr(0xCD) # Top edge
+ chr(0xBB) # Top right corner
+ '\n')
for row in xrange(9):
out += (' ' + chr(0xBA)) # Double Bar
for col in xrange(9):
n = board[posfor(row, col)]
if n is None:
out += ' '
else:
out += str(n+1)
if (col == 2) or (col == 5) or (col == 8):
out += chr(0xBA) # Double bar
else:
out += chr(0xB3) # Single bar
out += '\n'
if(row < 8):
if(row == 2) or (row == 5):
out += (' '
+ chr(0xCC) # Left 'T' (double)
+ chr(0xCD) # Horizontal bar
+ chr(0xD8) # +
+ chr(0xCD) # Horizontal bar
+ chr(0xD8) # +
+ chr(0xCD) # Horizontal bar
+ chr(0xCE) # Double +
+ chr(0xCD) # Horizontal bar
+ chr(0xD8) # +
+ chr(0xCD) # Horizontal bar
+ chr(0xD8) # +
+ chr(0xCD) # Horizontal bar
+ chr(0xCE) # Double +
+ chr(0xCD) # Horizontal bar
+ chr(0xD8) # +
+ chr(0xCD) # Horizontal bar
+ chr(0xD8) # +
+ chr(0xCD) # Horizontal bar
+ chr(0xB9) # Right 'T' (double)
+ '\n')
else:
out += (' '
+ chr(0xC7) # Left 'T'
+ chr(0xC4) # Horizontal bar
+ chr(0xC5) # +
+ chr(0xC4) # Horizontal bar
+ chr(0xC5) # +
+ chr(0xC4) # Horizontal bar
+ chr(0xD7) # Double +
+ chr(0xC4) # Horizontal bar
+ chr(0xC5) # +
+ chr(0xC4) # Horizontal bar
+ chr(0xC5) # +
+ chr(0xC4) # Horizontal bar
+ chr(0xD7) # Double +
+ chr(0xC4) # Horizontal bar
+ chr(0xC5) # +
+ chr(0xC4) # Horizontal bar
+ chr(0xC5) # +
+ chr(0xC4) # Horizontal bar
+ chr(0xB6) # Right 'T'
+ '\n')
out += (' '
+ chr(0xC8) # Bottom left corner
+ chr(0xCD) # Bottom edge
+ chr(0xCF) # Bottom 'T'
+ chr(0xCD) # Bottom edge
+ chr(0xCF) # Bottom 'T'
+ chr(0xCD) # Bottom edge
+ chr(0xCA) # Bottom 'T' (double)
+ chr(0xCD) # Bottom edge
+ chr(0xCF) # Bottom 'T'
+ chr(0xCD) # Bottom edge
+ chr(0xCF) # Bottom 'T'
+ chr(0xCD) # Bottom edge
+ chr(0xCA) # Bottom 'T' (double)
+ chr(0xCD) # Bottom edge
+ chr(0xCF) # Bottom 'T'
+ chr(0xCD) # Bottom edge
+ chr(0xCF) # Bottom 'T'
+ chr(0xCD) # Bottom edge
+ chr(0xBC) # Bottom-right corner
+ '\n')
# Original output code:
# out = ""
# for row in xrange(9):
# for col in xrange(9):
# out += (""," "," "," "," "," "," "," "," ")[col]
# out += printcode(board[posfor(row, col)])
# out += ('\n','\n','\n\n','\n','\n','\n\n','\n','\n','\n')[row]
return out
def parseboard(str):
result = []
for w in str.split():
for x in w:
if x in '|-=+': continue
if x in '123456789': result.append(int(x) - 1)
else: result.append(None)
if len(result) == 81: return result
def loadboard(filename):
f = file(filename, 'r')
result = parseboard(f.read())
f.close()
return result
def basedir():
if hasattr(sys.modules[__name__], '__file__'):
return os.path.split(__file__)[0]
elif __name__ == '__main__':
if len(sys.argv) > 0 and sys.argv[0] != '':
return os.path.split(sys.argv[0])[0]
else:
return os.curdir
def loadsudokutemplate(ext):
f = open(os.path.join(basedir(), 'sudoku-template.%s' % ext), 'r')
result = f.read()
f.close()
return result
if __name__ == '__main__':
main()