-
Notifications
You must be signed in to change notification settings - Fork 3
/
Sudoku.py
1733 lines (1575 loc) · 71.4 KB
/
Sudoku.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Sudoku.py
PADS-based command-line application for generating and solving Sudoku puzzles.
These puzzles are given as a 9x9 grid of cells, some of which are filled with
digits in the range 1-9. The task is to fill the remaining cells in such a
way that each row of the grid, each column of the grid, and each of nine 3x3
squares into which the grid is partitioned, all have one copy of each of the
nine digits.
A proper Sudoku puzzle must have a unique solution, and it should be possible
to reach that solution by a sequence of logical deductions without trial and
error. To the extent possible, we strive to keep the same ethic in our
automated solver, by mimicking human rule-based reasoning, rather than
resorting to brute force backtracking search.
D. Eppstein, July 2005.
"""
import random
import sys
from optparse import OptionParser
from BipartiteMatching import imperfections
from StrongConnectivity import StronglyConnectedComponents
from Repetitivity import NonrepetitiveGraph
from Wrap import wrap
from Not import Not
from TwoSatisfiability import Forced
from SVG import SVG
class BadSudoku(Exception): pass
# raised when we discover that a puzzle has no solutions
# ======================================================================
# Bitmaps and patterns
# ======================================================================
digits = range(1,10)
class group:
def __init__(self, i, j, x, y, name):
mask = 0
h,k = [q for q in range(4) if q != i and q != j]
for w in range(3):
for z in range(3):
mask |= 1 << (x*3**i + y*3**j + w*3**h + z*3**k)
self.mask = mask
self.pos = [None]*9
self.name = "%s %d" % (name,x+3*y+1)
cols = [group(0,1,x,y,"column") for x in range(3) for y in range(3)]
rows = [group(2,3,x,y,"row") for x in range(3) for y in range(3)]
sqrs = [group(1,3,x,y,"square") for x in range(3) for y in range(3)]
groups = sqrs+rows+cols
neighbors = [0]*81
for i in range(81):
b = 1<<i
for g in groups:
if g.mask & b:
neighbors[i] |= (g.mask &~ b)
unmask = {}
for i in range(81):
unmask[1<<i] = i
alignments = {}
for s in sqrs:
for g in rows+cols:
m = s.mask&g.mask
if m:
alignments[m] = (s,g)
b1 = m &~ (m-1)
m &=~ b1
b2 = m &~ (m-1)
b3 = m &~ b2
alignments[b1|b2]=alignments[b1|b3]=alignments[b2|b3]=(s,g)
triads = []
for square in sqrs:
for group in rows+cols:
triads.append((square.mask & group.mask,square,group))
# pairs of rows and columns that cross the same squares
nearby = {}
for g in rows+cols:
nearby[g] = []
for r1 in rows:
for s in sqrs:
if r1.mask & s.mask != 0:
for r2 in rows:
if r1 != r2 and r2.mask & s.mask != 0:
nearby[r1].append(r2)
break
for c1 in cols:
for s in sqrs:
if c1.mask & s.mask != 0:
for c2 in cols:
if c1.mask < c2.mask and c2.mask & s.mask != 0:
nearby[c1].append(c2)
break
FullPlacementGraph = {}
def searchPlacements(node,census):
if node in FullPlacementGraph:
return
FullPlacementGraph[node] = {}
for i in range(9):
b = 1<<i
if node & b:
continue # row already used, can't use it again
if census[i//3] > min(census):
continue # block already filled, can't use this row now
FullPlacementGraph[node][node|b] = 1<<(9*i+sum(census)) # found edge
census[i//3] += 1
searchPlacements(node|b,census) # recurse
census[i//3] -= 1
searchPlacements(0,[0,0,0])
# ======================================================================
# Human-readable names for puzzle cells
# ======================================================================
cellnames = [None]*81
for row in range(9):
for col in range(9):
cellnames[row*9+col] = ''.join(['R',str(row+1),'C',str(col+1)])
def andlist(list,conjunction="and"):
"""Turn list of strings into English text."""
if len(list) == 0:
return "(empty list!)"
if len(list) == 1:
return list[0]
elif len(list) == 2:
return (' '+conjunction+' ').join(list)
else:
return ', '.join(list[:-1]+[conjunction+' '+list[-1]])
def namecells(mask,conjunction="and"):
"""English string describing a sequence of cells."""
names = []
while mask:
bit = mask &~ (mask - 1)
names.append(cellnames[unmask[bit]])
mask &=~ bit
return andlist(names,conjunction)
def pathname(cells):
return '-'.join([cellnames[c] for c in cells])
def plural(howmany,objectname):
if howmany == 1:
return objectname
else:
return "%d %ss" % (howmany,objectname)
# ======================================================================
# State for puzzle solver
# ======================================================================
class Sudoku:
"""
Data structure for storing and manipulating Sudoku puzzles.
The actual rules for solving the puzzles are implemented
separately from this class.
"""
def __init__(self,initial_placements = None):
"""
Initialize a new Sudoku grid.
If an argument is given, it should either be a sequence of 81
digits 0-9 (0 meaning a not-yet-filled cell), or a sequence
of (digit,cell) pairs.
The main state we use for the solver is an array contents[]
of 81 cells containing digits 0-9 (0 for an unfilled cell)
and an array locations[] indexed by the digits 1-9, containing
bitmasks of the cells still available to each digit.
We also store additional fields:
- progress is a boolean, set whenever one of our methods
changes the state of the puzzle, and used by step() to tell
whether one of its rules fired.
- rules_used is a set of the rule names that have made progress.
- pairs is a dictionary mapping bitmasks of pairs of cells to
lists of digits that must be located in that pair, as set up
by the pair rule and used by other later rules.
- bilocation is a NonrepetitiveGraph representing paths and
cycles among bilocated digits, as constructed by the bilocal
rule and used by the repeat and conflict rules.
- bivalues is a NonrepetitiveGraph representing paths and
cycles among bivalued cells, as constructed by the bivalue
rule and used by the repeat and conflict rules.
- otherbv maps pairs (cell,digit) in the bivalue graph to the
other digit available at the same cell
- logstream is a stream on which to log verbose descriptions
of the steps made by the solver (typically sys.stderr), or
None if verbose descriptions are not to be logged.
- steps is used to count how many solver passes we've made so far.
- original_cells is a bitmask of cells that were originally nonempty.
- assume_unique should be set true to enable solution rules
based on the assumption that there exists a unique solution
- twosat should be set true to enable a 2SAT-based solution rule
"""
self.contents = [0]*81
self.locations = [None]+[(1<<81)-1]*9
self.rules_used = set()
self.progress = False
self.pairs = None
self.bilocation = None
self.logstream = False
self.steps = 0
self.original_cells = 0
self.assume_unique = False
self.twosat = False
if initial_placements:
cell = 0
for item in initial_placements:
try:
digit = int(item)
except TypeError:
digit,cell = item
if digit:
self.place(digit,cell)
self.original_cells |= 1 << cell
cell += 1
def __iter__(self):
"""
If we are asked to loop over the items in a grid
(for instance, if we pass one Sudoku instance as the argument
to the initialization of another one) we simply list the
known cell contents of the grid.
"""
return iter(self.contents)
def mark_progress(self):
"""Set progress True and clear fields that depended on old state."""
self.progress = True
self.pairs = None
def log(self,items,explanation=None):
"""
Send a message for verbose output.
Items should be a string or list of strings in the message.
If explanation is not None, it is called as a function and
the results appended to items.
"""
if not self.logstream:
return
if isinstance(items,str):
items = [items]
if explanation:
if isinstance(explanation,str) or isinstance(explanation,list):
x = explanation
else:
x = explanation()
if isinstance(x,str):
x = [x]
else:
x = []
text = ' '.join([str(i) for i in items+x])
for line in wrap(text):
self.logstream.write(line+'\n')
self.logstream.write('\n')
self.logstream.flush()
def place(self,digit,cell,explanation=None):
"""Change the puzzle by filling the given cell with the given digit."""
if digit != int(digit) or not 1 <= digit <= 9:
raise ValueError("place(%d,%d): digit out of range" % (digit,cell))
if self.contents[cell] == digit:
return
if self.contents[cell]:
self.log(["Unable to place",digit,"in",cellnames[cell],
"as it already contains",str(self.contents[cell])+"."])
raise BadSudoku("place(%d,%d): cell already contains %d" %
(digit,cell,self.contents[cell]))
if (1<<cell) & self.locations[digit] == 0:
self.log(["Unable to place",digit,"in",cellnames[cell],
"as that digit is not available to be placed there."])
raise BadSudoku("place(%d,%d): location not available" %
(digit,cell))
self.contents[cell] = digit
bit = 1 << cell
for d in digits:
if d != digit:
self.unplace(d,bit,explanation,False)
else:
self.unplace(d,neighbors[cell],explanation,False)
self.mark_progress()
self.log(["Placing",digit,"in",cellnames[cell]+'.'],explanation)
def unplace(self,digit,mask,explanation=None,log=True):
"""
Eliminate the masked positions as possible locations for digit.
The log argument should be true for external callers, but false
when called by Sudoku.place; it is used to disable verbose output
that would be redundant to the output from place.
"""
if digit != int(digit) or not 1 <= digit <= 9:
raise ValueError("unplace(%d): digit out of range" % digit)
if self.locations[digit] & mask:
if log and self.logstream:
items = ["Preventing",digit,"from being placed in",
namecells(self.locations[digit] & mask,"or")+'.']
self.log(items,explanation)
self.locations[digit] &=~ mask
self.mark_progress()
def choices(self,cell):
"""Which digits are still available to be placed in the cell?"""
bit = 1<<cell
return [d for d in digits if self.locations[d] & bit]
def complete(self):
"""True if all cells have been filled in."""
return 0 not in self.contents
# ======================================================================
# Rules for puzzle solver
# ======================================================================
def locate(grid):
"""
Place digits that can only go in one cell of their group.
If a digit x has only one remaining cell that it can be placed in,
within some row, column, or square, then we place it in that cell.
Any potential positions of x incompatible with that cell (because
they lie in the same row, column, or square) are removed from
future consideration.
"""
for d in digits:
for g in groups:
dglocs = grid.locations[d] & g.mask
if dglocs & (dglocs-1) == 0:
if dglocs == 0:
grid.log(["Unable to place",d,"anywhere in",g.name+"."])
raise BadSudoku("No place for %d in %s" %(d,g.name))
grid.place(d,unmask[dglocs],
["It is the only cell in",g.name,
"in which",d,"can be placed."])
def eliminate(grid):
"""
Fill cells that can only contain one possible digit.
If a cell has only one digit x that can be placed in it, we place
x in that cell. Incompatible positions for x are removed from
future consideration.
"""
for cell in range(81):
if not grid.contents[cell]:
allowed = grid.choices(cell)
if len(allowed) == 0:
grid.log(["Unable to place any digit in",cellnames[cell]+"."])
raise BadSudoku("No digit for cell %d" % cell)
if len(allowed) == 1:
grid.place(allowed[0],cell,
"No other digit may be placed in that cell.")
def align(grid):
"""
Eliminate positions that leave no choices for another group.
If the cells of a square that can contain a digit x all lie
in a single row or column, we eliminate positions for x that
are outside the square but inside that row or column. Similarly,
if the cells that can contain x within a row or column all lie
in a single square, we eliminate positions that are inside that
square but outside the row or column.
"""
for d in digits:
for g in groups:
a = grid.locations[d] & g.mask
if a in alignments:
s = [x for x in alignments[a] if x != g][0]
def explain():
un = grid.locations[d] & s.mask &~ a
if un & (un - 1):
this = "These placements"
else:
this = "This placement"
return [this, "would conflict with", namecells(a)+",",
"which are the only cells in", g.name,
"that can contain that digit."]
grid.unplace(d, s.mask &~ a, explain)
enough_room = "To leave enough room for those digits, no other " \
"digits may be placed in those cells."
def explain_pair(grid,digs,locs):
"""Concoct explanation for application of pair rule."""
d1,d2 = digs
g1 = [g for g in groups if
grid.locations[d1] & g.mask == grid.locations[d1] & locs]
g2 = [g for g in groups if
grid.locations[d2] & g.mask == grid.locations[d2] & locs]
for g in g1:
if g in g2:
ing = ["In", g.name+",", "digits", d1, "and", d2]
break
else:
# unlikely to get here due to align rule applying before pair
ing = ["In",(g1 and g1[0].name or "no group")+",", "digit", str(d1)+",",
"and in",(g2 and g2[0].name or "no group")+",", "digit", str(d2)]
return ing+["may only be placed in",namecells(locs)+".", enough_room]
def pair(grid):
"""
Eliminate positions that leave no choices for two other digits.
If two digits x and y each share the same two cells as the only
locations they may be placed within some row, column, or square,
then all other digits must avoid those two cells.
"""
grid.pairs = pairs = {}
for d in digits:
for g in groups:
dglocs = grid.locations[d] & g.mask
fewerbits = dglocs & (dglocs - 1)
if fewerbits & (fewerbits - 1) == 0:
if d not in pairs.setdefault(dglocs,[d]):
pairs[dglocs].append(d)
for e in digits:
if e not in pairs[dglocs]:
def explain():
return explain_pair(grid,pairs[dglocs],dglocs)
grid.unplace(e, dglocs, explain)
def triad(grid):
"""
Find forced triples of digits within triples of cells.
If some three cells, formed by intersecting a row or column
with a square, have three digits whose only remaining positions
within that row, column, or square are among those three cells,
we prevent all other digits from being placed there. We also
remove positions for those three forced digits outside the
triple but within the row, column, or square containing it.
"""
for mask,sqr,grp in triads:
forces = [d for d in digits
if (grid.locations[d]&sqr.mask == grid.locations[d]&mask)
or (grid.locations[d]&grp.mask == grid.locations[d]&mask)]
if len(forces) == 3:
outside = (sqr.mask | grp.mask) &~ mask
for d in digits:
def explain():
ing = ["In", grp.name, "and", sqr.name+",",
"digits %d, %d, and %d" % tuple(forces),
"may only be placed in", namecells(mask)+"."]
if d not in forces:
return ing+[enough_room]
elif grid.locations[d]&sqr.mask == grid.locations[d]&mask:
og = grp.name
else:
og = sqr.name
return ing+["Therefore,", d, "may not be placed",
"in any other cell of", og]
grid.unplace(d, d in forces and outside or mask, explain)
def nishio(grid):
"""
Remove incompatible positions of a single digit.
If the placement of digit x in cell y can not be extended to a
placement of nine copies of x covering each row, column, and
square of the grid exactly once, we eliminate cell y from
consideration as a placement for x.
"""
def search(v):
"""Simple recursive DFS to compute a set of reachable vertices.
Uses sets of visible and completable nodes in parent function,
and returns the union of edge labels on placement graph paths."""
visited.add(v)
result = 0
for w in FullPlacementGraph[v]: # for each potential neighbor
if locs & FullPlacementGraph[v][w]: # is it really a neighbor?
if w not in visited:
result |= search(w)
if w in completable:
completable.add(v)
result |= FullPlacementGraph[v][w]
return result
for d in digits:
visited = {511} # nodes no longer needing to be searched
completable = {511} # nodes with paths to the all-ones matrix
locs = grid.locations[d]
mask = search(0) # bitmask of cells in valid placements
if locs != mask:
def explain():
masked = locs &~ mask
if masked &~ (masked - 1):
ex = "These cells are"
else:
ex = "This cell is"
return ex + " not part of any valid placement of this digit that covers each row, column and 3x3 square exactly once."
grid.unplace(d, locs &~ mask, explain)
def rectangles():
"""Generate pairs of rows and columns that form two-square rectangles."""
for r1 in rows:
for r2 in rows:
if r2 in nearby[r1]:
for c1 in range(9):
for c2 in range(c1):
if cols[c1] not in nearby[cols[c2]]:
yield r1,r2,cols[c2],cols[c1]
elif r1.mask < r2.mask:
for c1 in cols:
for c2 in nearby[c1]:
yield r1,r2,c1,c2
def rectangle(grid):
"""
Avoid the formation of an ambiguous rectangle.
That is, four corners of a rectangle within two squares, all four
corners initially blank, and containing only two digits. If this
situation occurred, the puzzle would necessarily have evenly many
solutions, because we could swap the two digits in the rectangle
corners in any solution to form a different solution, contradicting
the assumption that there is only one. Therefore, we make sure that
any such rectangle keeps at least three available values.
"""
if not grid.assume_unique:
return
for r1,r2,c1,c2 in rectangles():
mask = (r1.mask | r2.mask) & (c1.mask | c2.mask)
if not (mask & grid.original_cells):
# First rectangle test
# If three cells are bivalued with the same two digits x,y
# then we can eliminate x and y on the fourth
safe_corners = 0
multiply_placable = []
for d in digits:
dmask = grid.locations[d] & mask
if dmask & (dmask - 1):
multiply_placable.append(d)
else:
safe_corners |= dmask
if len(multiply_placable) == 2 and \
safe_corners & (safe_corners-1) == 0:
for d in multiply_placable:
def explain():
return ["This placement would create an ambiguous",
"rectangle for digits",
str(multiply_placable[0]),"and",
str(multiply_placable[1]),"in",
r1.name+",",r2.name+",",
c1.name+",","and",c2.name+"."]
grid.unplace(d,safe_corners,explain)
# Second rectangle test
# If only three digits can be placed in the rectangle,
# we eliminate placements that conflict with
# all positions of one of the digits.
placable = [d for d in digits if grid.locations[d] & mask]
if len(placable) == 3:
for d in placable:
a = grid.locations[d] & mask
conflicts = 0
for g in groups:
if grid.locations[d] & g.mask & a == a:
conflicts |= g.mask
def explain():
un = conflicts &~ a
if un & (un - 1):
this = "These placements"
else:
this = "This placement"
return ["The rectangle in", r1.name+",",
r2.name+",", c1.name+", and", c2.name,
"can only contain digits",
andlist([str(dd) for dd in placable])+".",
this, "would conflict with the placements",
"of", str(d)+",", "creating an ambiguous",
"rectangle on the remaining two digits."]
grid.unplace(d, conflicts &~ a, explain)
# Third rectangle test
# If two cells are bivalued with digits x and y,
# and the other two cells are bilocal with x,
# then we can eliminate y from the two bilocal cells.
for x1,x2 in ((r1,r2), (r2,r1), (c1,c2), (c2,c1)):
xd = [d for d in digits if grid.locations[d] & mask & x1.mask]
if len(xd) == 2: # found locked pair on x1's corners
for d in xd:
x2d = grid.locations[d] & x2.mask
if x2d & mask == x2d: # and bilocal on x2
dd = xd[0]+xd[1]-d # other digit
def explain():
return ["The rectangle in", r1.name+",",
r2.name+",", c1.name+", and", c2.name,
"can only contain digits",
str(xd[0]),"and",str(xd[1]),"in",
x1.name+".","In addition,"
"the only cells in",x2.name,
"that can contain",str(d),
"are in the rectangle.",
"Therefore, to avoid creating an",
"ambiguous rectangle, the",str(dd),
"in",x2.name,"must be placed",
"outside the rectangle."]
grid.unplace(dd,x2d,explain)
# Fourth rectangle test
# If two cells are bivalued with digits x and y,
# and a perpendicular side is bilocal with x,
# then we can eliminate y from the remaining cell
for x1,perp in ((r1,(c1,c2)),(r2,(c1,c2)),
(c1,(r1,r2)),(c2,(r1,r2))):
xd = [d for d in digits if grid.locations[d] & mask & x1.mask]
if len(xd) == 2: # found locked pair on x1's corners
for x2 in perp:
for d in xd:
x2d = grid.locations[d] & x2.mask
if x2d & mask == x2d: # and bilocal on x2
dd = xd[0]+xd[1]-d # other digit
def explain():
return ["For the rectangle in", r1.name+",",
r2.name+",", c1.name+", and", c2.name,
"the two corners in",
x1.name,"must contain both digits",
str(xd[0]),"and",str(xd[1]),
"and the two corners in",
x2.name,"must contain one",str(d)+".",
"Therefore, to avoid creating an",
"ambiguous rectangle, the",
"remaining corner must not contain",
str(dd)+"."]
grid.unplace(dd,mask&~(x1.mask|x2.mask),explain)
def trapezoid(grid):
"""
Force pairs of digits to form trapezoids instead of rectangles.
If two digits can only be placed in five cells of two squares,
four of which form a rectangle, then they must be placed in
four cells that form a trapezoid out of those five.
We prevent those digits from being placed in cells not part of
a trapezoid, and prevent other digits from being placed in cells
that are part of all such trapezoids.
"""
if not grid.assume_unique:
return
for r1,r2,c1,c2 in rectangles():
corners = (r1.mask | r2.mask) & (c1.mask | c2.mask)
if not (corners & grid.original_cells):
s1,s2 = [s for s in sqrs if s.mask & corners]
uncorner = (s1.mask | s2.mask) &~ corners
candidates = {}
universal = None
for d in digits:
if not grid.locations[d] & uncorner:
universal = d # can form five cells w/any other digit
for d in digits:
locs_for_d = grid.locations[d] & uncorner
if locs_for_d and not (locs_for_d & (locs_for_d - 1)):
if universal != None or locs_for_d in candidates:
# found another digit sharing same five cells w/d
if universal != None:
d1,d2 = universal,d
else:
d1,d2 = candidates[locs_for_d],d
explanation = ["Digits",str(d1),"and",str(d2),
"must be placed in a trapezoid in",
s1.name,"and",s2.name+",",
"for if they were placed in a",
"rectangle, their locations",
"could be swapped, resulting",
"in multiple solutions",
"to the puzzle."]
must = locs_for_d
mustnt = 0
if s2.mask & locs_for_d:
s1,s2 = s2,s1 # swap so s1 contains extra cell
must |= corners & s2.mask
for line in r1.mask,r2.mask,c1.mask,c2.mask:
if line & locs_for_d and line & s2.mask:
# most informative case: the extra cell
# lies on a line through both squares.
must |= corners & (s1.mask &~ line)
mustnt |= corners & (s1.mask & line)
for d3 in digits:
if d3 == d1 or d3 == d2:
grid.unplace(d3,mustnt,explanation)
else:
grid.unplace(d3,must,explanation)
else:
candidates[locs_for_d] = d
def subproblem(grid):
"""
Remove incompatible positions within a single row, column, or square.
If the placement of a digit x in cell y within a single row, column,
or square can not be extended to a complete solution of that row, column,
or square, then we eliminate that placement from consideration.
"""
for g in groups:
graph = {}
for d in digits:
graph[d] = []
locs = grid.locations[d] & g.mask
while locs:
bit = locs &~ (locs-1)
graph[d].append(unmask[bit])
locs &=~ bit
imp = imperfections(graph)
for d in list(imp.keys()):
if not imp[d]:
del imp[d]
while imp:
# Here with imp mapping digits to unplaceable cells.
# We choose carefully the order of digits to handle,
# so that our explanations make logical sense: if an
# explanation includes the fact that a digit can only
# go in certain cells, we need to have already handled
# the unplaceable cells for that other digit.
for d in imp:
entailed = False
for cell in imp[d]:
for forced in imp[d][cell]:
if forced in imp and imp[forced]:
entailed = True
break
if not entailed:
break
# Here with imp[d] mapping d to some unplaceable cells.
# We build up a bitmap of those cells, as we do collecting
# the sets of digits and cells that must be matched to each
# other and that prevent us from placing d in those cells.
mask = 0
forces = []
for cell in imp[d]:
bit = 1<<cell
if bit & grid.locations[d]:
mask |= bit
force = imp[d][cell]
if force not in forces:
forces.append(force)
# Now that we have both the bitmap and the subgraphs describing
# why each bit is in that bitmap, we are ready to make and
# explain our unplacement decision.
def explain():
that = "would make it impossible to place that digit."
expls = []
for force in forces:
if expls or len(force) > 1:
that = "would leave too few remaining cells" \
" to place those digits."
if expls:
expls[-1] += ','
if force == forces[-1]:
expls[-1] += ' and'
forcedigs = [str(x) for x in force]
forcedigs.sort()
forcemask = 0
for dig in force:
for cell in force[dig]:
forcemask |= 1<<cell
expls += [len(forcedigs) == 1 and "digit" or "digits",
andlist(forcedigs), "can only be placed in",
namecells(forcemask)]
expls[-1] += '.'
return ["In", g.name+","] + expls + ["Placing", d,
"in", namecells(mask,"or"), that]
grid.unplace(d,mask,explain)
del imp[d]
if grid.progress:
return # let changes propagate before trying more groups
bilocal_explanation = \
"each two successive cells belong to a common row, column, or square," \
" and are the only two cells in that row, column, or square where one" \
" of the digits may be placed"
incyclic = "In the cyclic sequence of cells"
inpath = "In the sequence of cells"
def bilocal(grid):
"""
Look for nonrepetitive cycles among bilocated digits.
Despite the sesquipedalian summary line above, this is a form of
analysis that is easy to perform by hand: draw a graph connecting
two cells whenever some digit's location within a row, column,
or square is forced to lie only in those two cells. We then
search for cycles in the graph in which each two adjacent edges
in the cycle have different labels. In any such cycle, each cell
can only contain the digits labeling the two edges incident to it.
"""
if not grid.pairs:
return # can only run after pair rule finds edges
# Make labeled graph of pairs
graph = dict([(i,{}) for i in range(81)])
for pair in grid.pairs:
digs = grid.pairs[pair]
bit = pair &~ (pair-1)
pair &=~ bit
if pair:
v = unmask[bit]
w = unmask[pair]
graph[v][w] = graph[w][v] = digs
# Apply repetitivity analysis to collect cyclic labels at each cell
grid.bilocation = nrg = NonrepetitiveGraph(graph)
forced = [set() for i in range(81)]
for v,w,L in nrg.cyclic():
forced[v].add(L)
forced[w].add(L)
# Carry out forces indicated by our analysis
for cell in range(81):
if len(forced[cell]) == 2:
# It's also possible for len(forced[cell]) to be > 2;
# in this case multiple cycles go through the same edge
# and cell must be filled with the digit labeling that edge.
# But for simplicity's sake we ignore that possibility;
# it doesn't happen very often and when it does the repetitive
# cycle rule will find it instead.
mask = 1<<cell
for d in digits:
if d not in forced[cell]:
def explain():
forced1,forced2 = tuple(forced[cell])
cycle = nrg.shortest(cell,forced1,cell,forced2)
return [incyclic, pathname(cycle)+",",
bilocal_explanation + ".",
"This placement would prevent",
forced1, "or", forced2,
"from being placed in", cellnames[cell]+",",
"making it impossible to place the cycle's",
len(cycle)-1, "digits into the remaining",
len(cycle)-2, "cells."]
grid.unplace(d,mask,explain)
bivalue_explanation = \
"each cell has two possible digits, each of which may also" \
" be placed at one of the cell's two neighbors in the sequence"
def bivalue(grid):
"""
Look for nonrepetitive cycles among bivalued cells.
We draw a graph connecting two cells whenever both can only
contain two digits, one of those digits is the same for both
cells, and both cells belong to the same row, column, or square.
Edges are labeled by the digit(s) the two cells share.
If any edge of this graph is contained in a cycle with no two
consecutive edges having equal labels, then the digit labeling
that edge must be placed on one of its two endpoints, and can
not be placed in any other cell of the row, column, or square
containing the edge.
"""
# Find and make bitmask per digit of bivalued cells
graph = {}
grid.otherbv = otherbv = {}
tvmask = [0]*10
for c in range(81):
ch = grid.choices(c)
if len(ch) == 2:
graph[c] = {}
tvmask[ch[0]] |= 1<<c
tvmask[ch[1]] |= 1<<c
otherbv[c,ch[0]] = ch[1]
otherbv[c,ch[1]] = ch[0]
edgegroup = {}
# Form edges and map back to their groups
for g in groups:
for d in digits:
mask = tvmask[d] & g.mask
dgcells = []
while mask:
bit = mask &~ (mask - 1)
dgcells.append(unmask[bit])
mask &=~ bit
for v in dgcells:
for w in dgcells:
if v != w:
edgegroup.setdefault((v,w),[]).append(g)
graph[v].setdefault(w,set()).add(d)
# Apply repetitivity analysis to collect cyclic labels at each cell
# and eliminate that label from other cells of the same group
grid.bivalues = nrg = NonrepetitiveGraph(graph)
for v,w,digit in nrg.cyclic():
mask = 0
for g in edgegroup[v,w]:
mask |= g.mask
mask &=~ (1 << v)
mask &=~ (1 << w)
def explain():
cycle = [v] + nrg.shortest(w,grid.otherbv[w,digit],
v,grid.otherbv[v,digit])
return ["In the cyclic sequence of cells", pathname(cycle)+",",
bivalue_explanation + ".",
"This placement would conflict with placing", digit,
"in", namecells((1<<v)|(1<<w))+",",
"making it impossible to fill the cycle's",
len(cycle)-1, "cells with the remaining",
len(cycle)-2, "digits."]
grid.unplace(digit,mask,explain)
def repeat(grid):
"""
Look for cycles of bilocated or bivalued vertices with one repetition.
We use the same graphs described for the bilocal and bivalue rules;
if there exists a cycle in which some two adjacent edges are labeled
by the same digit, and all other adjacent pairs of cycle edges have
differing digits, then the repeated digit must be placed at the cell
where the two same-labeled edges meet (in the case of the bilocal graph)
or can be eliminated from that cell (in the case of the bivalue graph).
"""
if not grid.bilocation or not grid.bivalues:
return
for cell in range(81):
if not grid.contents[cell]:
for d in grid.choices(cell):
if (cell,d) in grid.bilocation.reachable(cell,d):
cycle = grid.bilocation.shortest(cell,d,cell,d)
if cycle[1] == cycle[-2]:
# Degenerate repetitive cycle, look for a better one.
# It would be a correct decision to place d in cell:
# due to prior application of the bilocal rule, the
# part of the cycle from cycle[1] to cycle[-2] must
# itself be a repetitive cycle. But the explanation
# will be clearer if we avoid using this cycle.
break
def explain():
expl = [incyclic, pathname(cycle)+",",
bilocal_explanation + ".",
"If",d,"were not placed in",cellnames[cell]+",",
"it would have to be placed in",
cellnames[cycle[1]],"and",
cellnames[cycle[-2]],"instead,",
"making it impossible to place the"]
if len(cycle) == 4:
expl.append("remaining digit.")
else:
expl += ["cycle's remaining",len(cycle)-3,"digits",
"in the remaining"]
if len(cycle) == 5:
expl.append("cell.")
else:
expl += [len(cycle)-4,"cells."]
return expl
grid.place(d,cell,explain)
return # allow changes to propagate w/simpler rules
elif (cell,d) in grid.bivalues.reachable(cell,d):
cycle = grid.bivalues.shortest(cell,d,cell,d)
if cycle[1] == cycle[-2]:
break
def explain():
return [incyclic, pathname(cycle)+",",
bivalue_explanation + ",",
"except that", cellnames[cell],
"shares", d, "as a possible value",
"with both of its neighbors.",
"Placing", d, "in", cellnames[cell],
"would make it impossible",
"to fill the cycle's remaining",
len(cycle)-2, "cells with the remaining",
len(cycle)-3, "digits, so only",
grid.otherbv[cell,d], "can be placed in",
cellnames[cell]+"."]
grid.place(grid.otherbv[cell,d],cell,explain)
return # allow changes to propagate w/simpler rules
def path(grid):
"""
Look for paths of bilocated or bivalued cells with conflicting endpoints.
In the same graphs used by the bilocal and repeat rules, if there exists
a path that starts and ends with the same digit, with no two consecutive
edges labeled by the same digit, then the digit ending the path can be
placed in no cell that conflicts with both endpoints of the path. If
the path endpoints belong to the same row, column, or square as each other,
this eliminates other placements within that row, column, or square;
otherwise, it eliminates placements at the other two corners of a
rectangle having the two path endpoints as opposite corners.
"""