2024-09-16_python-tredoku-solver.html


001| #:name::Python Tredoku Solver
002| #:link::https://thehardcorecoder.com/2024/09/16/python-tredoku-solver/
003| #:date::2024-09-16
004| #:code::
005| BlankPuzzle = {
006| (1,1):0,(1,2):0,(1,3):0,(1,4):0,(1,5):0,(1,6):0,(1,7):0,(1,8):0,(1,9):0,
007| (2,1):0,(2,2):0,(2,3):0,(2,4):0,(2,5):0,(2,6):0,(2,7):0,(2,8):0,(2,9):0,
008| (3,1):0,(3,2):0,(3,3):0,(3,4):0,(3,5):0,(3,6):0,(3,7):0,(3,8):0,(3,9):0,
009|                         (4,4):0,(4,5):0,(4,6):0,
010|                         (5,4):0,(5,5):0,(5,6):0,
011|                         (6,4):0,(6,5):0,(6,6):0,
012| (7,1):0,(7,2):0,(7,3):0,(7,4):0,(7,5):0,(7,6):0,(7,7):0,(7,8):0,(7,9):0,
013| (8,1):0,(8,2):0,(8,3):0,(8,4):0,(8,5):0,(8,6):0,(8,7):0,(8,8):0,(8,9):0,
014| (9,1):0,(9,2):0,(9,3):0,(9,4):0,(9,5):0,(9,6):0,(9,7):0,(9,8):0,(9,9):0,
015| }
016| 
017| PuzzlePaths = [
018|     [(1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(1,8),(1,9)], # Rows
019|     [(2,1),(2,2),(2,3),(2,4),(2,5),(2,6),(2,7),(2,8),(2,9)],
020|     [(3,1),(3,2),(3,3),(3,4),(3,5),(3,6),(3,7),(3,8),(3,9)],
021|     [(7,1),(7,2),(7,3),(7,4),(7,5),(7,6),(7,7),(7,8),(7,9)],
022|     [(8,1),(8,2),(8,3),(8,4),(8,5),(8,6),(8,7),(8,8),(8,9)],
023|     [(9,1),(9,2),(9,3),(9,4),(9,5),(9,6),(9,7),(9,8),(9,9)],
024| 
025|     [(1,4),(2,4),(3,4),(4,4),(5,4),(6,4),(7,7),(8,7),(9,7)], # Columns
026|     [(1,5),(2,5),(3,5),(4,5),(5,5),(6,5),(7,8),(8,8),(9,8)],
027|     [(1,6),(2,6),(3,6),(4,6),(5,6),(6,6),(7,9),(8,9),(9,9)],
028|     [(1,7),(2,7),(3,7),(4,6),(4,5),(4,4),(7,4),(8,4),(9,4)],
029|     [(1,8),(2,8),(3,8),(5,6),(5,5),(5,4),(7,5),(8,5),(9,5)],
030|     [(1,9),(2,9),(3,9),(6,6),(6,5),(6,4),(7,6),(8,6),(9,6)],
031| 
032|     [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)], # Squares
033|     [(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)],
034|     [(1,7),(1,8),(1,9),(2,7),(2,8),(2,9),(3,7),(3,8),(3,9)],
035|     [(7,1),(7,2),(7,3),(8,1),(8,2),(8,3),(9,1),(9,2),(9,3)],
036|     [(7,4),(7,5),(7,6),(8,4),(8,5),(8,6),(9,4),(9,5),(9,6)],
037|     [(7,7),(7,8),(7,9),(8,7),(8,8),(8,9),(9,7),(9,8),(9,9)],
038|     [(4,4),(4,5),(4,6),(5,4),(5,5),(5,6),(6,4),(6,5),(6,6)],
039| ]
040| 
041| #:code::
042| Puzzle1 = {
043|     (1,1):5, (1,2):2, (1,3):4, (1,4):1, (1,8):9,
044|     (2,1):7, (2,3):8, (2,5):4, (2,6):2,
045|     (3,2):6, (3,3):3, (3,6):9, (3,8):7,
046|     (4,5):5, (4,6):4,
047|     (6,4):7,
048|     (7,2):5, (7,3):4, (7,4):8, (7,6):9, (7,7):2,
049|     (8,1):3, (8,2):2, (8,3):1,
050|     (9,2):8, (9,3):6, (9,4):3, (9,6):2, (9,7):4, (9,9):5,
051| }
052| 
053| #:code::
054| from sys import stdout
055| 
056| Symbols = {n for n in range(1,10)}
057| RowSum = sum(Symbols)
058| 
059| GetRow = lambda pz,pd: [pz[k] for k in pd]
060| 
061| def join_puzzle (clues, blank=None) -> dict:
062|     '''Create a puzzle from a spec and a blank.'''
063|     if blank is None: blank = BlankPuzzle
064| 
065|     # Copy the blank...
066|     new_puzl = blank.copy()
067| 
068|     # Load the clues into blank puzzle...
069|     for key in clues:
070|         new_puzl[key] = clues[key]
071| 
072|     # Return joined puzzle...
073|     return new_puzl
074| 
075| def test_puzzle (puzl, pdef=None) -> bool:
076|     '''Test puzzle paths for being solved. Returns True or False.'''
077|     if pdef is None: pdef = PuzzlePaths
078| 
079|     # For every path definition...
080|     for px,pd in enumerate(pdef):
081| 
082|         # Get the values along the path...
083|         row = GetRow(puzl, pd)
084|         # And total them...
085|         tot = sum(row)
086| 
087|         # Fail on first mismatch...
088|         if tot != RowSum:
089|             return False
090| 
091|     # All good...
092|     return True
093| 
094| def print_puzzle (puzl, pdef=None, sout=None) -> list:
095|     '''List and add puzzle rows and columns.'''
096|     fout = stdout if sout is None else sout
097|     if pdef is None: pdef = PuzzlePaths
098| 
099|     accum = []
100|     # For every path definition...
101|     for px,pd in enumerate(pdef):
102| 
103|         # Get the values along the path...
104|         row = GetRow(puzl, pd)
105| 
106|         # Total row values; add sum to accumulator...
107|         tot = sum(row)
108|         accum.append((tot, row))
109| 
110|         # Print the puzzle row...
111|         status = 'Okay!' if sum(row) == RowSum else 'x'
112|         out = f'Path {px+1:2d}: {row} = {tot:2d} {status}'
113|         print(out, file=fout)
114| 
115|     print(file=fout)
116| 
117|     # Return list of rows...
118|     return accum
119| 
120| #:code::
121| class cellinfo:
122|     def __init__ (self, key):
123|         self.key = key
124|         self.pos = set()
125|         self.pds = []
126|         self.gots = []
127| 
128|     @property
129|     def size (self):
130|         '''Return number of possibilities.'''
131|         return len(self.pos)
132| 
133|     def __len__ (self):
134|         '''Return length of path defs list.'''
135|         return len(self.pds)
136| 
137|     def __iter__ (self):
138|         '''Return iterator for path defs list.'''
139|         return iter(self.pds)
140| 
141|     def __getitem__ (self, ix):
142|         '''Return item from path defs list.'''
143|         self.pds[ix]
144| 
145|     def __repr__ (self):
146|         '''Return simple string version.'''
147|         return f'{self.key}: {self.pos}'
148| 
149|     def __str__ (self):
150|         '''Return string version.'''
151|         s1 = ','.join(str(n) for n in self.key)
152|         s2 = ','.join(str(n) for n in self.pds)
153|         s3 = ''.join(str(n) for n in sorted(self.pos))
154|         gs = set()
155|         for g in self.gots:
156|             gs |= g
157|         s4 = ''.join(str(n) for n in sorted(gs))
158|         return f'{s1}: [{s2:<9s}] { {s3:8s}}  [{s4}]'
159| 
160| #:code::
161| from sys import stdout
162| from examples import Symbols, GetRow
163| 
164| def analyze_puzzle (puzl, pdef, sout=None) -> dict:
165|     '''Find and analyse puzzle.'''
166|     fout = stdout if sout is None else sout
167| 
168|     zcells = dict()
169| 
170|     # For each path definition...
171|     for px,pd in enumerate(pdef):
172|         row = GetRow(puzl, pd)
173|         got = set(row)
174|         if 0 in got:
175|             got.discard(0)
176| 
177|         # For each cell in the path...
178|         for key in pd:
179|             # Call value (skip filled in cells)...
180|             val = puzl[key]
181|             if 0 < val:
182|                 continue
183|             # Add pdef index to cell info...
184|             if key not in zcells: zcells[key] = cellinfo(key)
185|             zcells[key].pds.append(px)
186|             zcells[key].gots.append(got)
187| 
188|     # Populate possible entries for each zero...
189|     for zcel in zcells.values():
190|         # Merge gots...
191|         got = set()
192|         for g in zcel.gots:
193|             got |= g
194|         # Possibles are what's left...
195|         zcel.pos = Symbols - got
196| 
197|     # Print a listing...
198|     sortkey = lambda zc:(zc.size,zc.key)
199|     for zcel in sorted(zcells.values(), key=sortkey):
200|         print(zcel, file=fout)
201|     print(file=fout)
202| 
203|     # Return zero cell info objects...
204|     return zcells
205| 
206| #:code::
207| from sys import stdout
208| from examples import analyze_puzzle, test_puzzle
209| 
210| def solve_puzzle (puzl:dict, pdef:list=None, sout=None) -> tuple:
211|     '''Solve puzzle using logic.'''
212|     fout = stdout if sout is None else sout
213|     if pdef is None: pdef = PuzzlePaths
214| 
215|     zcells = analyze_puzzle(puzl, pdef, sout=sout)
216|     solved = False
217| 
218|     if len(zcells) == 0:
219|         solved = test_puzzle(puzl, pdef)
220|         return (solved, zcells)
221| 
222|     # List zero cells by least number of possible values...
223|     avail = list(sorted(zcells.values(), key=lambda ci:ci.size))
224| 
225|     # For each zero cell...
226|     for zcell in avail:
227| 
228|         # For each possible value, try it...
229|         for px,pos in enumerate(zcell.pos):
230|             puzl[zcell.key] = pos
231|             info = f'{px+1} of {zcell.size}'
232|             print(f'trying: {zcell.key} = {pos} ({info})\n', file=fout)
233| 
234|             # RECURSE...
235|             solved,_ = solve_puzzle(puzl, pdef, sout=sout)
236|             if solved:
237|                 break
238| 
239|             # Restore zero...
240|             puzl[zcell.key] = 0
241| 
242|         # Didn't solve it yet, try again...
243|         if solved:
244|             break
245| 
246|     # Return status and current zcell dictionary...
247|     return (solved, zcells)
248| 
249| #:code::
250| from examples import join_puzzle, print_puzzle, solve_puzzle
251| 
252| Clues1 = {
253|     (1,1):5, (1,2):2, (1,3):4, (1,4):1, (1,8):9,
254|     (2,1):7, (2,3):8, (2,5):4, (2,6):2,
255|     (3,2):6, (3,3):3, (3,6):9, (3,8):7,
256|     (4,5):5, (4,6):4,
257|     (6,4):7,
258|     (7,2):5, (7,3):4, (7,4):8, (7,6):9, (7,7):2,
259|     (8,1):3, (8,2):2, (8,3):1,
260|     (9,2):8, (9,3):6, (9,4):3, (9,6):2, (9,7):4, (9,9):5,
261| }
262| 
263| def do_puzzle_solve ():
264|     '''Solve puzzle logically.'''
265|     # Make puzzle...
266|     puzzle = join_puzzle(Clues1)
267|     print_puzzle(puzzle)
268| 
269|     fn = 'tredoku.list'
270|     fp = open(fn, mode='w')
271|     try:
272|         solved,zcells = solve_puzzle(puzzle, sout=fp)
273|         if solved:
274|             print('Puzzle solved!')
275|         else:
276|             print('Puzzle not solved.')
277|         print()
278| 
279|         print_puzzle(puzzle)
280|         print_puzzle(puzzle, sout=fp)
281| 
282|     except:
283|         raise
284|     finally:
285|         fp.close()
286|         print(f'wrote: {fn}')
287|         print()
288| 
289|     return (solved, puzzle, zcells)
290| 
291| do_puzzle_solve()
292| 
293| #:code::
294| from itertools import permutations
295| from examples import Symbols, GetRow
296| from examples import join_puzzle, test_puzzle, print_puzzle
297| 
298| Empty = '{}'
299| WatchDog = [0, 1_000_000]
300| 
301| def brute_solve_row (which, puzl, pdef) -> bool:
302|     '''Solve a puzzle row. (RECURSIVE)'''
303|     WatchDog[0] += 1
304|     if WatchDog[1] < WatchDog[0]:
305|         return True
306|     if len(pdef) <= which:
307|         return test_puzzle(puzl, pdef)
308| 
309|     # Get the cells along the path...
310|     row = GetRow(puzl, pdef[which])
311| 
312|     # If any digits are duplicated, we can't proceed...
313|     score = [0]*10
314|     for digit in row:
315|         score[digit] += 1
316|     high = max(score[1:])
317|     if 1 < high:
318|         return False
319| 
320|     # See what symbols we have...
321|     got = set(row)
322|     # If no zeros, row is full...
323|     if 0 not in got:
324|         flag = brute_solve_row(which+1, puzl, pdef)
325|         return
326| 
327|     # See what symbols are missing...
328|     got.discard(0)
329|     missing = got ^ Symbols
330| 
331|     # Try various combinations of missing symbols...
332|     perms = [list(p) for p in permutations(missing)]
333|     for ax,attempt in enumerate(perms):
334|         # Insert a permutation of solving the row...
335|         for val,key in zip(row, pdef[which]):
336|             # Insert where there are zeros...
337|             if val == 0:
338|                 puzl[key] = attempt.pop()
339|         assert len(attempt) == 0, RuntimeError()
340| 
341|         # Recurse to next row...
342|         flag = brute_solve_row(which+1, puzl, pdef)
343|         if flag:
344|             break
345| 
346|     # If next row always returned False...
347|     if not flag:
348|         # If unable to solve next path, restore our zeros...
349|         for val,key in zip(row, pdef[which]):
350|             if val == 0:
351|                 puzl[key] = 0
352|         return False
353| 
354|     # Return True for a good row...
355|     return test_puzzle(puzl, pdef)
356| 
357| 
358| def brute_solve_puzzle (puzl, pdef=None) -> bool:
359|     '''Solve the puzzle.'''
360|     if pdef is None: pdef = PuzzlePaths
361| 
362|     return brute_solve_row(0, puzl, pdef)
363| 
364| def solve_puzzle_brute ():
365|     '''Solve puzzle with brute force scan. (Takes forever!)'''
366|     # Make puzzle...
367|     puzzle = join_puzzle(Puzzle1)
368|     print_puzzle(puzzle)
369| 
370|     # Try to solve the puzzle...
371|     solved = solve_puzzle_brute(puzzle)
372|     if solved:
373|         print('Puzzle solved!')
374|     else:
375|         print('Puzzle not solved.')
376|     print()
377| 
378|     # Print puzzle to file and screen...
379|     print_puzzle(puzzle, sout=stdout)
380|     print_puzzle(puzzle)
381|     print()
382| 
383|     return solved
384| 
385| #:end:code::
386|