2024-09-16_python-tredoku-solver.html
001|
002|
003|
004|
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)],
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)],
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)],
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|
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|
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|
066| new_puzl = blank.copy()
067|
068|
069| for key in clues:
070| new_puzl[key] = clues[key]
071|
072|
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|
080| for px,pd in enumerate(pdef):
081|
082|
083| row = GetRow(puzl, pd)
084|
085| tot = sum(row)
086|
087|
088| if tot != RowSum:
089| return False
090|
091|
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|
101| for px,pd in enumerate(pdef):
102|
103|
104| row = GetRow(puzl, pd)
105|
106|
107| tot = sum(row)
108| accum.append((tot, row))
109|
110|
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|
118| return accum
119|
120|
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|
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|
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|
178| for key in pd:
179|
180| val = puzl[key]
181| if 0 < val:
182| continue
183|
184| if key not in zcells: zcells[key] = cellinfo(key)
185| zcells[key].pds.append(px)
186| zcells[key].gots.append(got)
187|
188|
189| for zcel in zcells.values():
190|
191| got = set()
192| for g in zcel.gots:
193| got |= g
194|
195| zcel.pos = Symbols - got
196|
197|
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|
204| return zcells
205|
206|
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|
223| avail = list(sorted(zcells.values(), key=lambda ci:ci.size))
224|
225|
226| for zcell in avail:
227|
228|
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|
235| solved,_ = solve_puzzle(puzl, pdef, sout=sout)
236| if solved:
237| break
238|
239|
240| puzl[zcell.key] = 0
241|
242|
243| if solved:
244| break
245|
246|
247| return (solved, zcells)
248|
249|
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|
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|
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|
310| row = GetRow(puzl, pdef[which])
311|
312|
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|
321| got = set(row)
322|
323| if 0 not in got:
324| flag = brute_solve_row(which+1, puzl, pdef)
325| return
326|
327|
328| got.discard(0)
329| missing = got ^ Symbols
330|
331|
332| perms = [list(p) for p in permutations(missing)]
333| for ax,attempt in enumerate(perms):
334|
335| for val,key in zip(row, pdef[which]):
336|
337| if val == 0:
338| puzl[key] = attempt.pop()
339| assert len(attempt) == 0, RuntimeError()
340|
341|
342| flag = brute_solve_row(which+1, puzl, pdef)
343| if flag:
344| break
345|
346|
347| if not flag:
348|
349| for val,key in zip(row, pdef[which]):
350| if val == 0:
351| puzl[key] = 0
352| return False
353|
354|
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|
367| puzzle = join_puzzle(Puzzle1)
368| print_puzzle(puzzle)
369|
370|
371| solved = solve_puzzle_brute(puzzle)
372| if solved:
373| print('Puzzle solved!')
374| else:
375| print('Puzzle not solved.')
376| print()
377|
378|
379| print_puzzle(puzzle, sout=stdout)
380| print_puzzle(puzzle)
381| print()
382|
383| return solved
384|
385|
386|