eight_queens.html
001| '''The Eight Queens Chess Puzzle.'''
002|
003| from sys import argv, stdout
004| from os import path
005|
006| BasePath = r'C:\CJS\prj\Python\app\chess'
007|
008| NROWS = 8
009| NCOLS = 8
010| QUEEN = 1
011| STATS = [0, 0, 0, 0]
012|
013|
014|
015| class chessboard (object):
016| def __init__ (self, nrows=8, ncols=8):
017| self.nr = nrows
018| self.nc = ncols
019| self.bd = [[0 for cx in range(ncols)] for rx in range(nrows)]
020|
021| def row (self, row):
022| if 0 <= row < self.nr:
023| return self.bd[row]
024| return []
025|
026| def col (self, col):
027| if 0 <= col < self.nc:
028| return [b[col] for b in self.bd]
029| return []
030|
031| def __getitem__ (self, row_col):
032| row,col = row_col
033| if 0 <= row < self.nr:
034| if 0 <= col < self.nc:
035| return self.bd[row][col]
036| return 0
037|
038| def __setitem__ (self, row_col, value):
039| row,col = row_col
040| if 0 <= row < self.nr:
041| if 0 <= col < self.nc:
042| self.bd[row][col] = value
043|
044| def __str__ (self):
045| a = ['%s\n' % row for row in self.bd]
046| return ''.join(a)
047|
048|
049|
050| def record_board_position (board, NR=NROWS, NC=NCOLS, fp=stdout):
051| STATS[0] += 1
052|
053| fp.flush()
054| divider = ' +%s \n' % ('---+'*NC)
055| fp.write(divider)
056| for rx in range(NR):
057| fp.write(' |')
058| for cx in range(NC):
059| s = ' Q |' if board[rx,cx] == QUEEN else ' |'
060| fp.write(s)
061| fp.write('\n')
062| fp.write(divider)
063| fp.write('\n')
064| fp.flush()
065|
066|
067| def check_board_layout (board, NR=NROWS, NC=NCOLS):
068| STATS[1] += 1
069|
070|
071| for rx in range(NR):
072| cells = board.row(rx)
073| if QUEEN < sum(cells): return False
074|
075| for cx in range(NC):
076| cells = board.col(cx)
077| if QUEEN < sum(cells): return False
078|
079| for rx in range(NR-1):
080| cells = [board[rx+cx, cx] for cx in range(NC-rx)]
081| if QUEEN < sum(cells): return False
082| cells = [board[rx+cx, NC-cx-1] for cx in range(NC-rx)]
083| if QUEEN < sum(cells): return False
084| for cx in range(1, NC-1):
085| cells = [board[rx, cx+rx] for rx in range(NR-cx)]
086| if QUEEN < sum(cells): return False
087| cells = [board[rx, NR-(cx+rx)-1] for rx in range(NR-cx)]
088| if QUEEN < sum(cells): return False
089|
090| return True
091|
092|
093| def check_queen_position (board, row,col, NR=NROWS, NC=NCOLS):
094| STATS[1] += 1
095|
096| for ix in range(max(NR,NC)):
097| rx0, rx1 = row-ix, row+ix
098| cx0, cx1 = col-ix, col+ix
099| if board[row,cx0] == QUEEN: return False
100| if board[row,cx1] == QUEEN: return False
101| if board[rx0,col] == QUEEN: return False
102| if board[rx1,col] == QUEEN: return False
103| if board[rx0,cx0] == QUEEN: return False
104| if board[rx0,cx1] == QUEEN: return False
105| if board[rx1,cx0] == QUEEN: return False
106| if board[rx1,cx1] == QUEEN: return False
107| return True
108|
109|
110| def add_queen_to_board (board, row,col, NR=NROWS, NC=NCOLS):
111| STATS[1] += 1
112|
113| if board[row,col]:
114| return False
115| board[row,col] = QUEEN
116| for ix in range(1,max(NR,NC)):
117| rx0, rx1 = row-ix, row+ix
118| cx0, cx1 = col-ix, col+ix
119| mask = 1 << col
120| board[row,cx0] |= mask
121| board[row,cx1] |= mask
122| board[rx0,col] |= mask
123| board[rx1,col] |= mask
124| board[rx0,cx0] |= mask
125| board[rx0,cx1] |= mask
126| board[rx1,cx0] |= mask
127| board[rx1,cx1] |= mask
128| return True
129|
130| def remove_queen_from_board (board, row,col, NR=NROWS, NC=NCOLS):
131| STATS[2] += 1
132|
133| board[row,col] = 0
134| for ix in range(1,max(NR,NC)):
135| rx0, rx1 = row-ix, row+ix
136| cx0, cx1 = col-ix, col+ix
137| mask = ~(1 << col)
138| board[row,cx0] &= mask
139| board[row,cx1] &= mask
140| board[rx0,col] &= mask
141| board[rx1,col] &= mask
142| board[rx0,cx0] &= mask
143| board[rx0,cx1] &= mask
144| board[rx1,cx0] &= mask
145| board[rx1,cx1] &= mask
146|
147|
148|
149| def find_queens_1 (board, level=0, NR=NROWS, NC=NCOLS, fp=stdout):
150| ''' Place a queen on a given level (aka column).'''
151|
152|
153| for row in range(NR):
154|
155| if (level==0) and ((NR//2) <= row):
156| break
157|
158| board[row,level] = QUEEN
159|
160| if check_board_layout(board, NR,NC):
161|
162| if level == (NC-1):
163|
164| record_board_position(board, NR,NC, fp)
165| else:
166|
167| find_queens_1(board, level+1, NR,NC, fp)
168|
169| board[row,level] = 0
170|
171|
172| def find_queens_2 (board, level=0, NR=NROWS, NC=NCOLS, fp=stdout):
173| ''' Place a queen on a given level (aka column).'''
174|
175|
176| for row in range(NR):
177|
178| if (level==0) and ((NR//2) <= row):
179| break
180|
181| if check_queen_position(board, row,level, NR,NC):
182| board[row,level] = QUEEN
183|
184| if level == (NC-1):
185|
186| record_board_position(board, NR,NC, fp)
187| else:
188|
189| find_queens_2(board, level+1, NR,NC, fp)
190|
191| board[row,level] = 0
192|
193|
194| def find_queens_3 (board, level=0, NR=NROWS, NC=NCOLS, fp=stdout):
195| ''' Place a queen on a given level (aka column).'''
196|
197|
198| for row in range(NR):
199|
200| if (level==0) and ((NR//2) <= row):
201| break
202|
203| if add_queen_to_board(board, row,level, NR,NC):
204|
205| if level == (NC-1):
206|
207| record_board_position(board, NR,NC, fp)
208| else:
209|
210| find_queens_3(board, level+1, NR,NC, fp)
211|
212| remove_queen_from_board(board, row,level, NR,NC)
213|
214|
215|
216| def report_solution (accum, NR=NROWS, NC=NCOLS, fp=stdout):
217| STATS[0] += 1
218|
219| fp.flush()
220|
221| fp.write(' %s:\n' % accum)
222| divider = ' +%s \n' % ('---+'*NC)
223| fp.write(divider)
224| for rx in range(NR):
225| row = rx + 1
226|
227| fp.write(' |')
228| for cx in range(NC):
229| s = ' Q |' if accum[cx] == row else ' |'
230| fp.write(s)
231| fp.write('\n')
232| fp.write(divider)
233| fp.write('\n')
234| fp.flush()
235|
236|
237| def check_row (accum, row, NR=NROWS, NC=NCOLS, fp=stdout):
238| STATS[1] += 1
239|
240|
241| if row in accum:
242| return 0
243|
244| for ix,ch in enumerate(reversed(accum)):
245| n = row + (ix + 1)
246| if NR < n:
247| break
248| if n == ch:
249| return 0
250|
251| for ix,ch in enumerate(reversed(accum)):
252| n = row - (ix + 1)
253| if n < 1:
254| break
255| if n == ch:
256| return 0
257|
258| return 1
259|
260|
261| def find_queens_4 (accum=[], NR=NROWS, NC=NCOLS, fp=stdout):
262| for row in [r+1 for r in range(NR)]:
263|
264| if (len(accum) == 0) and (int((NR+1)/2) < row):
265| break
266| if check_row(accum, row, NR,NC, fp):
267|
268| accum.append(row)
269| if len(accum) == NC:
270|
271| report_solution(accum, NR,NC, fp)
272| else:
273|
274| find_queens_4(accum, NR,NC, fp)
275|
276| accum.pop()
277|
278|
279|
280| def do_old_1 (*args):
281| print('old-1')
282| nr = int(args[0]) if 0 < len(args) else NROWS
283| nc = int(args[1]) if 1 < len(args) else NCOLS
284|
285| fn = args[2] if 2 < len(args) else path.join(BasePath,'eight_queens_1.out')
286| fp = open(fn, mode='w', encoding='utf-8')
287| try:
288| bd = chessboard()
289| find_queens_1(bd, NR=nr, NC=nc, fp=fp)
290| print(file=fp)
291| print("STATS: %s" % str(STATS), file=fp)
292| print(file=fp)
293| except Exception:
294| raise
295| finally:
296| fp.close()
297| return 'Done'
298|
299|
300| def do_old_2 (*args):
301| print('old-2')
302| nr = int(args[0]) if 0 < len(args) else NROWS
303| nc = int(args[1]) if 1 < len(args) else NCOLS
304| bd = [[int(0) for c in range(nc)] for r in range(nr)]
305|
306| fn = args[2] if 2 < len(args) else path.join(BasePath,'eight_queens_2.out')
307| fp = open(fn, mode='w', encoding='utf-8')
308| try:
309| bd = chessboard()
310| find_queens_2(bd, NR=nr, NC=nc, fp=fp)
311| print(file=fp)
312| print("STATS: %s" % str(STATS), file=fp)
313| print(file=fp)
314| except Exception:
315| raise
316| finally:
317| fp.close()
318| return 'Done'
319|
320|
321| def do_old_3 (*args):
322| print('old-3')
323| nr = int(args[0]) if 0 < len(args) else NROWS
324| nc = int(args[1]) if 1 < len(args) else NCOLS
325| bd = [[int(0) for c in range(nc)] for r in range(nr)]
326|
327| fn = args[2] if 2 < len(args) else path.join(BasePath,'eight_queens_3.out')
328| fp = open(fn, mode='w', encoding='utf-8')
329| try:
330| bd = chessboard()
331| find_queens_3(bd, NR=nr, NC=nc, fp=fp)
332| print(file=fp)
333| print("STATS: %s" % str(STATS), file=fp)
334| print(file=fp)
335| except Exception:
336| raise
337| finally:
338| fp.close()
339| return 'Done'
340|
341|
342| def do_test (*args):
343| print('test')
344| nr = int(args[0]) if 0 < len(args) else NROWS
345| nc = int(args[1]) if 1 < len(args) else NCOLS
346| fn = args[2] if 2 < len(args) else path.join(BasePath,'eight_queens.out')
347| fp = open(fn, mode='w', encoding='utf-8')
348| try:
349| find_queens_4(fp=fp)
350| print(file=fp)
351| print("STATS: %s" % str(STATS), file=fp)
352| print(file=fp)
353| except Exception:
354| raise
355| finally:
356| fp.close()
357| return 'Done'
358|
359| def do_main (*args):
360| print('main')
361| fn = args[0] if 0 < len(args) else path.join(BasePath,'eight_queens.out')
362| fp = open(fn, mode='w', encoding='utf-8')
363| try:
364| find_queens_4(fp=fp)
365| print(file=fp)
366| print("STATS: %s" % str(STATS), file=fp)
367| print(file=fp)
368| except Exception:
369| raise
370| finally:
371| fp.close()
372| return 'Done'
373|
374| def dispatch (cmd, *args):
375| print('command: %s' % cmd)
376| for ix,a in enumerate(args): print('argument[%d]: %s' % (ix,a))
377| print()
378|
379| if cmd == 'old1': return do_old_1(*args)
380| if cmd == 'old2': return do_old_2(*args)
381| if cmd == 'old3': return do_old_3(*args)
382| if cmd == 'test': return do_test(*args)
383| if cmd == 'main': return do_main(*args)
384| return 'Nothing to do!'
385|
386| if __name__ == '__main__':
387| print('autorun: %s' % argv[0])
388| cmd = argv[1] if 1 < len(argv) else 'main'
389| etc = argv[2:] if 2 < len(argv) else []
390| obj = dispatch(cmd, *etc)
391| print("STATS: %s" % str(STATS))
392| print(obj)
393|
394| '''eof'''
395|