tredoku.html
001| '''Tredoku -- "3D" Sudoku Puzzle Solver.
001|
001| https://substack.com/@beyondeuclid/note/c-104895678
001|
001| Classes:
001| cellinfo
001|
001| Functions:
001| solve_puzzle (puzl, pdefs, depth) -Solve puzzle using logic.
001| analyze_puzzle (puzl, pdefs, sout, quiet) -Find and analyse puzzle.
001| print_puzzle (puzl, pdef, sout) -List puzzle rows and columns.
001| test_puzzle (puzl, pdef) -Test puzzle paths.
001|
001| get_puzzle (name, which, fname, fpath) -Get puzzle definition.
001|
001| Commands:
001| pp do_puzzle_print
001| pa do_puzzle_analyze
001| ps do_puzzle_solve
001|
001| '''
002|
003| from sys import argv, stdout
004| from os import path
005| from itertools import permutations
006| from logger import logger, info, debug, trace
007| from files import linefile, jsonfile
008|
009| BasePath = r'C:\CJS\prj\Python\app\maths'
010| DataPath = path.join(BasePath, 'dat')
011| ListPath = path.join(BasePath, 'out')
012| Log = logger('tredoku')
013|
014|
015| Symbols = {n for n in range(1,10)}
016| RowSum = sum(Symbols)
017|
018| GetRow = lambda pz,pd: [pz[k] for k in pd]
019|
020|
021| class cellinfo:
022| '''Contains information about a specific puzzle cell.'''
023|
024| def __init__ (self, key):
025| self.key = key
026| self.pos = set()
027| self.pds = []
028| self.gots = []
029|
030| @property
031| def size (self):
032| '''Return number of possibilities.'''
033| return len(self.pos)
034|
035| def __len__ (self):
036| '''Return length of path defs list.'''
037| return len(self.pds)
038|
039| def __iter__ (self):
040| '''Return iterator for path defs list.'''
041| return iter(self.pds)
042|
043| def __getitem__ (self, ix):
044| '''Return item from path defs list.'''
045| self.pds[ix]
046|
047| def __repr__ (self):
048| '''Return simple string version.'''
049| return f'{self.key}: {self.pos}'
050|
051| def __str__ (self):
052| '''Return string version.'''
053| s1 = ','.join(str(n) for n in self.key)
054| s2 = ','.join(str(n) for n in self.pds)
055| s3 = ''.join(str(n) for n in sorted(self.pos))
056| gs = set()
057| for g in self.gots:
058| gs |= g
059| s4 = ''.join(str(n) for n in sorted(gs))
060| return f'{s1}: [{s2:<9s}] { {s3:8s}} [{s4}]'
061|
062|
063|
064| def get_puzzle (name:str, which:int=0, fname:str='puzzles.json', fpath:str=DataPath) -> dict:
065| '''\
065| Get puzzle definition from JSON file and merge clues to make new puzzle.
065|
065| parameters:
065| name :str -name of puzzle package
065| which :int -index of specific puzzle
065| fname :str -JSON filename (can include fullpath/filename)
065| fpath :str -pathname (or ''|None if fname contains path)
065|
065| returns:
065| :tuple (puzzle, path-defs)
065| '''
066|
067|
068| fn = path.join(fpath,fname) if fpath else fname
069| fo = jsonfile(fn)
070| fo.load()
071| Log.debug(f'get-puzzle: {name}[{which}]')
072|
073|
074| puzdef = fo.data[name]
075|
076| puzzle = {(int(r),int(c)):0 for r,c in puzdef['blank']}
077|
078| pdefs = [[(int(r),int(c)) for r,c in row] for row in puzdef['paths']]
079|
080| clues = {(int(r),int(c)):int(v) for r,c,v in puzdef['puzzles'][which]}
081|
082|
083| for key in clues:
084| puzzle[key] = clues[key]
085|
086|
087| return (puzzle, pdefs)
088|
089|
090|
091| def test_puzzle (puzl:dict, pdef:list) -> bool:
092| '''Test puzzle paths by checking their sum. Returns: True (solved) or False.'''
093|
094|
095| for px,pd in enumerate(pdef):
096|
097|
098| row = GetRow(puzl, pd)
099|
100| tot = sum(row)
101|
102|
103| if tot != RowSum:
104| return False
105|
106|
107| return True
108|
109|
110|
111| def print_puzzle (puzl:dict, pdef:list, sout=None) -> list:
112| '''List puzzle rows and columns (with row/col sums). Returns list of rows.'''
113| Log.debug('print-puzzle')
114|
115| accum = []
116|
117| for px,pd in enumerate(pdef):
118|
119|
120| row = GetRow(puzl, pd)
121|
122|
123| tot = sum(row)
124| accum.append((tot, row))
125|
126|
127| status = 'Okay!' if sum(row) == RowSum else 'x'
128| out = f'Path {px+1:2d}: {row} = {tot:2d} {status}'
129| if sout is None:
130| Log.info(out)
131| else:
132| print(out, file=sout)
133|
134|
135| if sout is None:
136| Log.info()
137| else:
138| print(file=sout)
139|
140|
141| return accum
142|
143|
144|
145| def analyze_puzzle (puzl:dict, pdefs:list, sout=None, quiet=False) -> dict:
146| '''Analyse puzzle. Returns dict of cellinfo objects for blank cells.'''
147|
148| zcells = dict()
149|
150|
151| for px,pd in enumerate(pdefs):
152| row = GetRow(puzl, pd)
153| got = set(row)
154| if 0 in got:
155| got.discard(0)
156|
157|
158| for key in pd:
159|
160| val = puzl[key]
161| if 0 < val:
162| continue
163|
164| if key not in zcells: zcells[key] = cellinfo(key)
165| zcells[key].pds.append(px)
166| zcells[key].gots.append(got)
167|
168|
169| for zcel in zcells.values():
170|
171| got = set()
172| for g in zcel.gots:
173| got |= g
174|
175| zcel.pos = Symbols - got
176|
177|
178| if not quiet:
179| for zcel in sorted(zcells.values(), key=lambda zc:(zc.size,zc.key)):
180| if sout is None:
181| Log.info(zcel)
182| else:
183| print(zcel, file=sout)
184|
185|
186| if sout is None:
187| Log.info()
188| else:
189| print(file=sout)
190|
191|
192| return zcells
193|
194|
195| def solve_puzzle (puzl:dict, pdefs:list, depth=0) -> tuple:
196| '''Recursive puzzle solver Returns tuple(solved-puzzle,zcells).'''
197| Log.trace(f'solve-puzzle: enter ({depth=})')
198|
199|
200| zcells = analyze_puzzle(puzl, pdefs, quiet=True)
201| solved = False
202|
203|
204| if len(zcells) == 0:
205|
206| solved = test_puzzle(puzl, pdefs)
207| Log.debug(f'No Zero Cells! ({solved=})')
208|
209| return (solved, zcells)
210|
211|
212| avail = list(sorted(zcells.values(), key=lambda zc:(zc.size,zc.key)))
213|
214|
215| if avail[0].size == 0:
216| Log.trace(f'Blocked Cell {avail[0].key}')
217|
218| return (False, zcells)
219|
220|
221| for zcell in avail:
222|
223|
224| for px,pos in enumerate(zcell.pos):
225| puzl[zcell.key] = pos
226| info = f'{px+1} of {zcell.size}'
227| Log.trace(f'trying[{depth:3d}]: {zcell.key} = {pos} ({info})')
228| Log.trace()
229|
230|
231|
232| solved,_ = solve_puzzle(puzl, pdefs, depth+1)
233|
234| if solved:
235| break
236|
237|
238| puzl[zcell.key] = 0
239|
240|
241| if solved:
242| break
243|
244|
245|
246|
247| Log.trace(f'solve-puzzle: exit ({solved=})')
248| return (solved, zcells)
249|
250|
251|
252| def do_puzzle_solve (*args):
253| '''CMD: Solve a puzzle.'''
254| pname = args[0] if 0 < len(args) else 'tredoku1'
255| which = int(args[1]) if 1 < len(args) else 0
256| Log.info(f'puzzle-solve: {pname}[{which}]')
257| Log.info()
258|
259|
260| puzzle,pdefs = get_puzzle(pname, which)
261| print_puzzle(puzzle, pdefs)
262|
263|
264| solved,zcells = solve_puzzle(puzzle, pdefs)
265| if solved:
266| Log.info('Puzzle solved!')
267| print('Puzzle solved!')
268| else:
269| Log.info('Puzzle not solved.')
270| print('Puzzle not solved.')
271| Log.info()
272| print()
273|
274|
275| print_puzzle(puzzle, pdefs, sout=stdout)
276| print_puzzle(puzzle, pdefs)
277|
278|
279| fn = path.join(BasePath, 'tredoku.list')
280| fp = open(fn, mode='w')
281| try:
282| print(f'Puzzle: {pname}[{which}]', file=fp)
283| if solved:
284| print('Puzzle solved!')
285| else:
286| print('Puzzle not solved.')
287| print(file=fp)
288|
289| print_puzzle(puzzle, pdefs, sout=fp)
290| except:
291| raise
292| finally:
293| fp.close()
294|
295| return (solved, puzzle, zcells)
296|
297| def do_puzzle_analyze (*args):
298| '''CMD: Analyze a puzzle.'''
299| pname = args[0] if 0 < len(args) else 'tredoku1'
300| which = int(args[1]) if 1 < len(args) else 0
301| Log.info(f'puzzle-analyse: {pname}[{which}]')
302| Log.info()
303|
304|
305| puzzle,pdefs = get_puzzle(pname, which)
306|
307|
308| print_puzzle(puzzle, pdefs, sout=stdout)
309| print_puzzle(puzzle, pdefs)
310|
311|
312| analyze_puzzle(puzzle, pdefs, sout=stdout)
313| analyze_puzzle(puzzle, pdefs)
314|
315|
316| fn = path.join(BasePath, 'tredoku.list')
317| fp = open(fn, mode='w')
318| try:
319| print(f'Puzzle: {pname}[{which}]', file=fp)
320| print(file=fp)
321|
322| print_puzzle(puzzle, pdefs, sout=fp)
323| analyze_puzzle(puzzle, pdefs, sout=fp)
324| except:
325| raise
326| finally:
327| fp.close()
328|
329| return (puzzle, pdefs)
330|
331| def do_puzzle_print (*args):
332| '''CMD: Print a puzzle.'''
333| pname = args[0] if 0 < len(args) else 'tredoku1'
334| which = int(args[1]) if 1 < len(args) else 0
335| Log.info(f'puzzle-print: {pname}[{which}]')
336| Log.info()
337|
338|
339| puzzle,pdefs = get_puzzle(pname, which)
340|
341|
342| print_puzzle(puzzle, pdefs)
343| print_puzzle(puzzle, pdefs, sout=stdout)
344|
345|
346| fn = path.join(BasePath, 'tredoku.list')
347| fp = open(fn, mode='w')
348| try:
349| print(f'Puzzle: {pname}[{which}]', file=fp)
350| print(file=fp)
351| print_puzzle(puzzle, pdefs, sout=fp)
352| except:
353| raise
354| finally:
355| fp.close()
356|
357| return puzzle
358|
359| def dispatch (cmd, *args):
360| Log.info(f'command: "{cmd}"')
361| Log.info()
362| if cmd == 'pp': return do_puzzle_print(*args)
363| if cmd == 'pa': return do_puzzle_analyze(*args)
364| if cmd == 'ps': return do_puzzle_solve(*args)
365| return ()
366|
367| if __name__ == '__main__':
368| print('autorun: %s' % argv[0])
369| Log.start(path.join(BasePath,'tredoku.log'))
370| Log.level(debug())
371| Log.info(argv[0])
372| Log.info()
373| cmnd = argv[1] if 1 < len(argv) else 'pa'
374| args = argv[2:] if 2 < len(argv) else ['sudoku', '6']
375|
376| rv = dispatch(cmnd, *args)
377| print()
378|
379| '''eof'''
380|