Subversion Repositories programming

Rev

Rev 409 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
405 ira 1
#!/usr/bin/env python
2
 
3
__author__    = "Ira W. Snyder (devel@irasnyder.com)"
4
__copyright__ = "Copyright (c) 2006, Ira W. Snyder (devel@irasnyder.com)"
5
__license__   = "GNU GPL v2 (or, at your option, any later version)"
6
 
408 ira 7
from PyCompat import *
8
 
406 ira 9
import sys
405 ira 10
import copy
408 ira 11
import time
405 ira 12
 
13
#
14
# Domain class.
15
#
16
# This will hold the domain for each place in the SudokuPuzzle class.
17
#
18
 
19
class SudokuDomain (object):
20
 
21
	DEFAULT = [1, 2, 3, 4, 5, 6, 7, 8, 9]
22
 
23
	def __init__ (self, domain=None):
24
		self.domain = self.DEFAULT[:]
25
		self.used = False
26
 
27
		if domain:
28
			self.domain = domain
29
 
30
	def __repr__ (self):
31
		if len(self.domain) == 0:
32
			return 'E'
33
		elif len(self.domain) == 1:
34
			return str(self.domain[0])
35
		else:
36
			return ' '
37
 
38
	def remove_value (self, value, strict=False):
39
		if strict:
40
			if value not in self.domain:
41
				raise ValueError
42
 
407 ira 43
		if value not in self.domain:
44
			return False
45
		else:
46
			self.domain = [i for i in self.domain if i != value]
47
			return True
405 ira 48
 
49
	def set_value (self, value):
50
		self.domain = [value]
51
 
52
	def is_singleton (self):
53
		if self.get_len() == 1:
54
			return True
55
 
56
		return False
57
 
58
	def is_empty (self):
59
		if self.get_len () == 0:
60
			return True
61
 
62
		return False
63
 
64
	def get_len (self):
65
		return len(self.domain)
66
 
67
	def get_value (self):
68
		"""Only works if this is a singleton"""
69
		if not self.is_singleton ():
70
			raise ValueError
71
 
72
		return self.domain[0]
73
 
74
#
75
# SudokuPuzzle class.
76
#
77
# This will hold all of the current domains for each position in a sudoku
78
# puzzle, and allow each value to be retrieved by its row,col pair.
79
# This access can be done by using SudokuPuzzle[0,0] to access the first
80
# element, and SudokuPuzzle[8,8] to access the last element.
81
#
82
 
83
class SudokuPuzzle (object):
84
 
407 ira 85
	def __init__ (self, puzzle=None, printing_enabled=True):
405 ira 86
		"""Can possibly take an existing puzzle to set the state"""
87
		self.__state = []
88
 
89
		if puzzle:
90
			self.__state = puzzle.__state[:]
91
		else:
92
			for i in xrange(81):
93
				self.__state.append (SudokuDomain())
94
 
407 ira 95
		self.printing_enabled = printing_enabled
96
 
405 ira 97
	def __getitem__ (self, key):
98
		row, col = key
99
		return self.__state [row*9+col]
100
 
101
	def __setitem__ (self, key, value):
102
		row, col = key
103
		self.__state [row*9+col] = value
104
		return value
105
 
106
	def __repr__ (self):
107
		s = ''
108
 
109
		for i in xrange (9):
110
			if i % 3 == 0:
111
				s += '=' * 25
112
				s += '\n'
113
 
114
			for j in xrange (9):
115
				if j % 3 == 0:
116
					s += '| '
117
 
118
				s += '%s ' % str(self[i,j])
119
 
120
			s += '|\n'
121
 
122
		s += '=' * 25
123
		return s
124
 
125
	def __iter__ (self):
410 ira 126
		return self.__state.__iter__
405 ira 127
 
128
	def valid_index (self, index):
129
		if index < 0 or index > 8:
130
			return False
131
 
132
		return True
133
 
134
	def get_row (self, row, col):
135
		"""Return a list that represents the list that $row is a part of.
136
		This will exclude the element at $row."""
137
		if not self.valid_index (row) or not self.valid_index (col):
138
			raise ValueError # Bad index
139
 
140
		li = []
141
		for i in xrange(9):
142
			if i != col:
143
				li.append (self[row,i])
144
 
145
		return li
146
 
147
	def get_col (self, row, col):
148
		"""Return a list that represents the list that $col is a part of.
149
		This will exclude the element at $col."""
150
		if not self.valid_index (row) or not self.valid_index (col):
151
			raise ValueError # Bad index
152
 
153
		li = []
154
		for i in xrange(9):
155
			if i != row:
156
				li.append (self[i,col])
157
 
158
		return li
159
 
160
	def get_upper_left (self, row, col):
161
		"""Return the row and column of the upper left part of the small
162
		box that contains self[row,col]."""
163
		new_row = row / 3 * 3
164
		new_col = col / 3 * 3
165
 
166
		return (new_row, new_col)
167
 
168
	def get_small_square (self, row, col):
169
		"""Return a list that represents the small square that (row, col) is a
170
		member of. This will exclude the element at (row, col)."""
171
 
172
		(ul_row, ul_col) = self.get_upper_left (row, col)
173
		li = []
174
 
175
		for i in xrange(ul_row, ul_row+3):
176
			for j in xrange(ul_col, ul_col+3):
177
				if not (i == row and j == col):
178
					li.append (self[i,j])
179
 
180
		return li
181
 
182
	def prune (self, row, col, value):
183
		"""Remove all occurances of $value from all of the places
184
		it cannot be in sudoku for the element at (row, col)."""
185
 
186
		for e in self.get_row (row, col):
407 ira 187
			if e.remove_value (value):
188
				self.print_domain_changed (e, value)
405 ira 189
 
190
		for e in self.get_col (row, col):
407 ira 191
			if e.remove_value (value):
192
				self.print_domain_changed (e, value)
405 ira 193
 
194
		for e in self.get_small_square (row, col):
407 ira 195
			if e.remove_value (value):
196
				self.print_domain_changed (e, value)
405 ira 197
 
198
	def puzzle_is_solved (self):
199
		for i in xrange(9):
200
			for j in xrange(9):
201
				if not self[i,j].is_singleton ():
202
					return False
203
 
204
		return True
205
 
206
	def puzzle_is_failed (self):
207
		for i in xrange(9):
208
			for j in xrange(9):
209
				if self[i,j].is_empty ():
210
					return True
211
 
212
		return False
213
 
407 ira 214
	def print_domain_changed (self, value, removed_val):
215
		if not self.printing_enabled:
216
			return
217
 
218
		for i in xrange(9):
219
			for j in xrange(9):
220
				if self[i,j] is value:
221
					print 'removed %d from (%d, %d) -> %s' % \
222
						(removed_val, i, j, value.domain)
223
 
224
	def print_generic (self, s):
225
		if not self.printing_enabled:
226
			return
227
 
228
		print s
229
 
230
 
406 ira 231
def solve (puzzle):
408 ira 232
 
233
	# Print the puzzle we're trying to solve
234
	puzzle.print_generic ('\nTrying to solve:')
235
	puzzle.print_generic ('%s\n' % str(puzzle))
236
 
406 ira 237
	changed = True
405 ira 238
 
407 ira 239
	# The main Arc Consistency Algorithm implementation
406 ira 240
	while changed:
241
		changed = False
242
		for i in xrange(9):
243
			for j in xrange(9):
244
				e = puzzle[i,j]
245
				if e.is_singleton () and e.used == False:
246
					puzzle.prune (i, j, e.get_value ())
247
					e.used = True
248
					changed = True
405 ira 249
 
407 ira 250
					# Check if we failed during the last pruning pass
251
					if puzzle.puzzle_is_failed ():
252
						puzzle.print_generic ('Puzzle failed, null entry created!')
253
						return False
405 ira 254
 
407 ira 255
	# Check if we're finished with the puzzle
406 ira 256
	if puzzle.puzzle_is_solved ():
407 ira 257
		puzzle.print_generic ('Puzzle finished! wheee!')
406 ira 258
		return puzzle
405 ira 259
 
407 ira 260
	### Find the smallest node in the puzzle. The smallest node
261
	### is the best cantidate to split.
406 ira 262
	size = sys.maxint
263
	smallest_rc = (10, 10)
405 ira 264
 
406 ira 265
	for i in xrange(9):
266
		for j in xrange(9):
267
			e = puzzle[i,j]
268
			if not e.is_singleton ():
269
				if e.get_len () < size:
270
					size = e.get_len ()
271
					smallest_rc = (i, j)
405 ira 272
 
407 ira 273
	### SPLIT TIME!
406 ira 274
	(r, c) = smallest_rc
275
	spl = puzzle[r,c].get_len ()
405 ira 276
 
406 ira 277
	lhalf = puzzle[r,c].domain[:spl/2]
278
	rhalf = puzzle[r,c].domain[spl/2:]
405 ira 279
 
407 ira 280
	# Split Message
281
	puzzle.print_generic ('splitting at %s (size=%d) -> %s and %s' % \
282
			(smallest_rc, size, lhalf, rhalf))
283
 
284
	# Solve the "left" half
406 ira 285
	lcopy = copy.deepcopy (puzzle)
286
	lcopy[r,c] = SudokuDomain (lhalf)
407 ira 287
	leftsolve = solve(lcopy)
405 ira 288
 
407 ira 289
	# If it solved correctly, then return it back up
406 ira 290
	if leftsolve:
291
		return leftsolve
405 ira 292
 
407 ira 293
	# Solve the "right" half
406 ira 294
	rcopy = copy.deepcopy (puzzle)
295
	rcopy[r,c] = SudokuDomain (rhalf)
407 ira 296
	rightsolve = solve (rcopy)
405 ira 297
 
407 ira 298
	# If it solved correctly, then return it back up
406 ira 299
	if rightsolve:
300
		return rightsolve
405 ira 301
 
407 ira 302
	# Both splits at this level failed, time to work our way back up the tree
303
	puzzle.print_generic ('Both splits at this level failed, back up!')
406 ira 304
	return False
405 ira 305
 
406 ira 306
 
307
 
405 ira 308
def main ():
309
	s = SudokuPuzzle ()
310
 
311
	print 'Enter a row at a time. Use \'e\' for empty squares.'
312
	for i in xrange(9):
313
		e = raw_input('line %d: ' % i)
314
		temp = e.split ()
315
 
316
		count = 0
317
		for j in temp:
318
			try:
319
				s[i,count].set_value (int(j))
320
			except:
321
				pass
322
 
323
			count += 1
324
 
408 ira 325
	tstart = time.time ()
326
	solution = solve (s)
327
	tend = time.time ()
407 ira 328
	print '\nThe solution is:'
408 ira 329
	print str(solution)
330
	print
331
	print 'Took %s seconds to solve' % str(tend - tstart)
405 ira 332
 
333
if __name__ == '__main__':
334
	main ()