-
Notifications
You must be signed in to change notification settings - Fork 0
/
str8ts.py
executable file
·2378 lines (2140 loc) · 99.6 KB
/
str8ts.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
#!/usr/bin/env python
from itertools import combinations, tee, product
from collections import Counter, defaultdict as DefaultDict
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from copy import deepcopy
from fnmatch import fnmatch
from textwrap import dedent
from timeit import default_timer as timer
from re import sub as re_sub
BLACK = "#"
UNKNOWN = [".", " ", "*"]
ALL = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
BLACK_ALL = "abcdefghi"
ACROSS = "123456789"
DOWN = "ABCDEFGHI"
def _pass(s):
print("\033[40;92mPASS\033[0m {}".format(s))
def _fail(s):
print("\033[40;91mFAIL\033[0m {}".format(s))
def _todo(s):
print("\033[103;30mTODO\033[0m {}".format(s))
def _hit(s):
print("\033[100;92mHIT\033[0m {}".format(s))
def _caution(s):
print("\033[107;92mCAUTION\033[0m {}".format(s))
def _miss(s):
print("\033[100;31mMISS\033[0m {}".format(s))
def _critical(s):
print("\033[101;97mCRITICAL\033[0m {}".format(s))
def _comment(s):
print("\033[100;97m# {:<88}\033[0m".format(s))
def _info(s):
print("\033[100;34mINFO\033[0m {}".format(s))
######################################################################################################################
# Cell and ProxyCell classes
class Cell(object):
def __init__(self, digits):
self.black = False
self.given = False
self.digits = []
self.removed = set()
self.sure_candidates_by_row = set()
self.sure_candidates_by_col = set()
for d in digits:
if d == BLACK:
self.black = True
elif d in BLACK_ALL:
self.black = True
self.digits.append(str(ord(d) - 96))
elif d in ALL:
self.digits.append(d)
self.given = True
elif d in UNKNOWN:
self.digits.extend(ALL)
if len(self.digits) == 1:
self.known = True
else:
self.known = False
def __str__(self):
if self.is_known():
digit = self.digits[0]
else:
digit = " "
if self.black:
return "\033[40;97m{}\033[0m".format(digit)
elif self.given:
return "\033[107;94m{}\033[0m".format(digit)
elif self.is_known():
return "\033[107;30m{}\033[0m".format(digit)
else:
return "\033[100;30m \033[0m"
def __repr__(self):
if self.black:
parts = ["\033[40;97m"]
elif self.is_unknown():
parts = ["\033[100;30m"]
elif self.is_known():
parts = ["\033[107;30m"]
elif self.given:
parts = ["\033[107;94m"]
else:
parts = ["\033[100;30m"]
for x in ALL:
if x in self.removed:
parts.append("\033[31m{}\033[30m".format(x))
elif x in self.digits:
if self.is_known():
parts.append(x)
else:
sc_row = x in self.sure_candidates_by_row
sc_col = x in self.sure_candidates_by_col
if sc_row and sc_col:
parts.append("\033[42m{}\033[100m".format(x))
elif sc_row:
parts.append("\033[43m{}\033[100m".format(x))
elif sc_col:
parts.append("\033[46m{}\033[100m".format(x))
else:
parts.append(x)
else:
parts.append(" ")
parts.append("\033[0m")
self.removed.clear()
return "".join(parts)
def match(self, other):
if self.is_black():
if other in BLACK_ALL:
return self.digits[0] == str(ord(other) - 96)
else:
return other == BLACK
else:
return set(self.digits) == set([d for d in other])
def is_black(self):
return self.black
def is_white(self):
return not self.black
def is_known(self):
return self.known
def is_unknown(self):
return not self.known and not self.black
def value(self):
assert self.is_known()
return self.digits[0]
def can_not_be(self, n):
if self.is_unknown():
for d in n:
if d in self.digits:
self.digits.remove(d)
self.removed.add(d)
if d in self.sure_candidates_by_row:
self.sure_candidates_by_row.remove(d)
if d in self.sure_candidates_by_col:
self.sure_candidates_by_col.remove(d)
if len(self.digits) == 1:
self.known = True
def value_is(self, n):
assert n in self.digits
for d in self.digits:
if d != n:
self.removed.add(d)
self.digits = [n]
self.known = True
def get_sc_by_row(self):
return self.sure_candidates_by_row
def get_sc_by_col(self):
return self.sure_candidates_by_col
class ProxyCell(object):
def __init__(self, digits, cell):
self.digits = set(digits)
self.cell = cell
def can_not_be(self, n):
self.cell.can_not_be(n)
######################################################################################################################
# Solver functions
def generate_compartments_by_cell(cells):
compartments = []
compartment = []
for c in cells:
if c.is_white():
compartment.append(c)
elif compartment:
compartments.append(compartment)
compartment = []
else:
if compartment:
compartments.append(compartment)
return compartments
def compartment_range_check_by_cells(compartment):
reach = len(compartment) - 1
# Digit: 1 2 3 4 5 6 7 8 9
# Count: 2 2 2 2 4 4 4 5 5
# Min: 2 - - - 2 1 - - -
# +-> 1-1 - - 1-2 - - -
# +-> 1-1 - - 1-1-1 - -
# x x|- - - - - - -
# For each cell we test is any other cell contains digits that are out of range.
lowest = set()
highest = set()
for c in compartment:
min_digit_index = ALL.index(min(c.digits))
while min_digit_index < 9 and min_digit_index in lowest:
min_digit_index += 1
else:
lowest.add(min_digit_index)
max_digit_index = ALL.index(max(c.digits))
while max_digit_index >= 0 and max_digit_index in highest:
max_digit_index -= 1
else:
highest.add(max_digit_index)
digits_out_of_range = ALL[: max(max(lowest) - reach, 0)] + ALL[min(highest) + reach + 1 :]
if digits_out_of_range:
for c in compartment:
c.can_not_be(digits_out_of_range)
def sure_candidates_by_cells(compartment, line, sc_fn):
union = set()
for c in compartment:
union.update(sc_fn(c))
if union:
# We can remove the sure candidates from all other cells outside of the compartment
for c in line:
if c in compartment:
continue
else:
c.can_not_be(union)
def singles_by_cell(compartment, sc_fn):
# Search for singles in the sure candidates
digit_in_cells = DefaultDict(set)
for c in compartment:
for d in sc_fn(c):
digit_in_cells[d].add(c)
# If any sure candidate is only in one cell, then cell is the sure candidate
for d, cells in digit_in_cells.items():
if len(cells) == 1:
c = cells.pop()
c.value_is(d)
def stranded_digits_by_cells(compartment):
def yield_groups(union_of_compartment):
g = []
for n in ALL:
if n in union_of_compartment:
g.append(n)
elif g:
yield g
g = []
else:
if g:
yield (g)
# We now union the available digits in the group.
union = set()
for c in compartment:
union.update(c.digits)
len_compartment = len(compartment)
for g in yield_groups(union):
if len(g) < len_compartment:
# The compartment doesn't fit into this group.
# Remove all digits of the group from the compartment digits.
for d in g:
for c in compartment:
c.can_not_be(d)
def bridging_digits_by_cells(compartment):
siblings = {"1": "2", "2": "13", "3": "24", "4": "35", "5": "46", "6": "57", "7": "68", "8": "79", "9": "8"}
if len(compartment) > 1:
for cell in compartment:
remove = set()
for d in cell.digits:
searching_for = siblings[d]
# We check in another cell can touch this digit.
hit = False
for c in compartment:
if c != cell:
for s in searching_for:
if s in c.digits:
hit = True
break
if hit:
break
else:
remove.add(d)
for d in remove:
cell.can_not_be(d)
def stranded_by_bridge_by_cells(compartment):
counts = Counter()
for c in compartment:
for d in c.digits:
counts[d] += 1
# Search for a cell that has multiple singles
for c in compartment:
singles = set(d for d in c.digits if counts[d] == 1)
if len(singles) > 1:
# If a single can only be in a solution *including* another solution, then it is removed.
len_compartment = len(compartment)
min_digit, max_digit = min(counts), max(counts)
min_digit_index, max_digit_index = ALL.index(min_digit), ALL.index(max_digit)
solutions = [
ALL[i : i + len_compartment] for i in range(min_digit_index, max_digit_index + 2 - len_compartment)
]
isolated_singles = set()
for s in solutions:
found_singles = set(single for single in singles if single in s)
if len(found_singles) == 1:
isolated_singles.update(found_singles)
for s in singles:
if s not in isolated_singles:
# This single is illegal.
for c in compartment:
c.can_not_be(s)
def naked_groups_by_cells(cells):
# For each line we consider all combinations searching for naked groups
for r in range(len(cells), 1, -1):
for combination in combinations(cells, r):
digits = set()
for c in combination:
digits.update(c.digits)
if len(digits) == r:
# We need to check that there isn't another cell which can be added to this group,
# if so, it would have all it's digits removed.
for c in cells:
if c in combination:
continue
elif not digits.issuperset(c.digits):
# We have a naked group. Exclude this digits from the other cells.
c.can_not_be(digits)
def split_compartments_by_cells(compartment):
steps = [
naked_groups_by_cells, # yes
# ??? We want to add this to the test, but it takes a whole board not the split cells
# unique_rectangle_rule,
]
union = set()
for c in compartment:
union.update(c.digits)
for g in ALL:
if g not in union:
below = set(d for d in union if d < g)
above = set(d for d in union if d > g)
if below and above:
# print('Split compartment col:{}{} below:{} gap:{} above:{}'.format(x, compartment, below, g, above))
above_cells = [ProxyCell(below.intersection(c.digits), c) for c in compartment]
below_cells = [ProxyCell(above.intersection(c.digits), c) for c in compartment]
for s in steps:
s(above_cells)
s(below_cells)
def mind_the_gap_by_cells(cells):
def _pairwise(iter):
a, b = tee(iter)
next(b, None)
return zip(a, b)
# We search for cells with a large gap
# Gap is 'large' if the distance is >= the compartment size
len_compartment = len(cells)
for cell in cells:
for d1, d2 in _pairwise(cell.digits):
index_d1, index_d2 = ALL.index(d1), ALL.index(d2)
if index_d2 - index_d1 >= len_compartment:
if not set(ALL[:index_d1]).intersection(cell.digits):
# These numbers can't be in the other cells
for c in cells:
if c != cell:
c.can_not_be(d1)
if not set(ALL[index_d2 + 1 :]).intersection(cell.digits):
# These numbers can't be in the other cells
for c in cells:
if c != cell:
c.can_not_be(d2)
def mind_the_bridging_gap_by_cells(cells):
len_compartment = len(cells)
small_cells = [c for c in cells if len(c.digits) == 2]
# We search for 2 cells with only 2 digits, a shared digit and a large gap
for combination in combinations(small_cells, 2):
a_digits = set(combination[0].digits)
b_digits = set(combination[1].digits)
bridge = a_digits.intersection(b_digits)
if len(bridge) == 1:
a_index = ALL.index(a_digits.difference(bridge).pop())
b_index = ALL.index(b_digits.difference(bridge).pop())
if (a_index > b_index and a_index - b_index >= len_compartment) or (b_index - a_index >= len_compartment):
# We can remove the bridge from all other cells
for c in cells:
if c not in combination:
c.can_not_be(bridge)
def hidden_group_by_cells(compartment, sc_fn):
union = set()
for c in compartment:
union.update(sc_fn(c))
if union:
for r in range(2, len(union)):
for combination in combinations(union, r):
# We count the cells that have contain these sure candidates
cells = set()
for c in compartment:
for d in combination:
if d in c.digits:
cells.add(c)
break
# If the # of cells containing the combination is equal
if len(cells) == r:
can_not_be = set(ALL)
can_not_be.difference_update(combination)
# Then we remove all the other candidates from the cells.
for c in cells:
c.can_not_be(can_not_be)
def hidden_group_by_cross_cells(compartment, sure_candidates):
for r in range(2, len(sure_candidates)):
for combination in combinations(sure_candidates, r):
# We count the cells that have contain these sure candidates
cells = set()
for c in compartment:
for d in combination:
if d in c.digits:
cells.add(c)
break
# If the # of cells containing the combination is equal
if len(cells) == r:
can_not_be = set(ALL)
can_not_be.difference_update(combination)
# Then we remove all the other candidates from the cells.
for c in cells:
c.can_not_be(can_not_be)
def sure_candidate_upgrade_by_cells(compartments, sure_candidates, sc_fn):
hit = False
for d in sure_candidates:
# If d is only in 1 compartment then it is a sure candidate.
compartment_count = 0
for compartment in compartments:
for cell in compartment:
if d in cell.digits:
compartment_count += 1
break
if compartment_count == 1:
for compartment in compartments:
for cell in compartment:
if d in cell.digits and d not in sc_fn(cell):
sc_fn(cell).add(d)
hit = True
return hit
def sure_candidate_range_check_by_cells(compartment, sc_fn):
# We need to make sure that all digits are within range of the sure candidates.
sc_for_compartment = [sc_fn(c) for c in compartment if sc_fn(c)]
if sc_for_compartment:
sc_min = min(min(sc) for sc in sc_for_compartment)
sc_max = max(max(sc) for sc in sc_for_compartment)
sc_min_index = ALL.index(sc_min)
sc_max_index = ALL.index(sc_max)
len_compartment = len(compartment)
out_of_range = ALL[: max(sc_max_index - len_compartment + 1, 0)] + ALL[sc_min_index + len_compartment :]
if out_of_range:
if False:
print("compartment", compartment)
print("sc for compartment", sc_for_compartment)
print("out of range", out_of_range)
for c in compartment:
c.can_not_be(out_of_range)
######################################################################################################################
# Board class
class Board(dict):
def __init__(self, board, chain_length=4):
if isinstance(board, list):
for ny, y in enumerate(DOWN):
for nx, x in enumerate(ACROSS):
try:
digits = board[ny][nx]
except:
digits = BLACK
self[x, y] = Cell(digits)
else:
for y, line in enumerate(board.splitlines()):
for x, c in enumerate(line):
self[ACROSS[x], DOWN[y]] = Cell(c)
self.chain_length = chain_length
# Generate and store compartments
self.compartments_by_row = self._generate_compartments_by_row()
self.compartments_by_col = self._generate_compartments_by_col()
# Generate and store the sure candidates
self.sure_candidates_by_cross_row = DefaultDict(set)
self.sure_candidates_by_cross_col = DefaultDict(set)
self._sure_candidates_by_row()
self._sure_candidates_by_col()
# Known digits
self._known_cells = {}
# Counters to tracking the solver
self.counts = Counter()
self.hits = Counter()
self.durations = DefaultDict(float)
######################################################################################################################
# Methods to generate and iterate the compartments
def _generate_compartments_by_row(self):
return {y: generate_compartments_by_cell([self[x, y] for x in ACROSS]) for y in DOWN}
def _generate_compartments_by_col(self):
return {x: generate_compartments_by_cell([self[x, y] for y in DOWN]) for x in ACROSS}
def _iter_compartments_by_row(self):
for y in DOWN:
for c in self.compartments_by_row[y]:
yield y, c
def _iter_compartments_by_col(self):
for x in ACROSS:
for c in self.compartments_by_col[x]:
yield x, c
def _iter_cross_but(self, x, y):
for dx in ACROSS:
if dx == x:
continue
yield (dx, y), self[dx, y]
for dy in DOWN:
if dy == y:
continue
yield (x, dy), self[x, dy]
def _iter_all_but(self, x, y):
for dx in ACROSS:
if dx == x:
continue
for dy in DOWN:
if dy == y:
continue
yield (dx, dy), self[dx, dy]
######################################################################################################################
# Methods to generate the sure candidates
def _sure_candidates_by_row(self, remove_unusable=False):
for y in DOWN:
if len(self.compartments_by_row[y]) > 1:
compartment_combinations = []
total_length = 0
for compartment in self.compartments_by_row[y]:
# Generate a sorted list of all the digits used in the compartment.
union = set()
for c in compartment:
union.update(c.digits)
union_list = sorted(union)
# Generate all possible combinations of str8ts for the compartment.
len_compartment = len(compartment)
c_combinations = []
for n in range(1 + len(union_list) - len_compartment):
index_start = ALL.index(union_list[n])
index_end = ALL.index(union_list[n + len_compartment - 1])
if index_end - index_start == len_compartment - 1:
c_combinations.append(set(union_list[n : n + len_compartment]))
# These are stored for each compartment.
compartment_combinations.append(c_combinations)
total_length += len_compartment
# If we have more than 1 compartment we make all the possible combinations that are legal.
row_unions = []
legal_compartments = [[] for c in compartment_combinations]
for combinations in product(*compartment_combinations):
union = set.union(*combinations)
# Is a legal combination
if len(union) == total_length:
# Make a union for the row
row_unions.append(union)
# Add the legal combinations to their compartment lists.
for n, c in enumerate(combinations):
legal_compartments[n].append(c)
row_union = set.intersection(*row_unions)
self.sure_candidates_by_cross_row[y].update(row_union)
for n, legal_unions in enumerate(legal_compartments):
compartment_union = set.union(*legal_unions)
compartment_intersection = set.intersection(*legal_unions)
for c in self.compartments_by_row[y][n]:
if remove_unusable:
for d in c.digits:
if d not in compartment_union:
c.can_not_be(d)
c.sure_candidates_by_row.update(compartment_intersection)
c.sure_candidates_by_row.intersection_update(c.digits)
else:
for compartment in self.compartments_by_row[y]:
union = set()
for c in compartment:
union.update(c.digits)
index_min = ALL.index(min(union))
index_max = ALL.index(max(union)) + 1 # Required for correct range
len_compartment = len(compartment)
lowest_range = set(ALL[index_min : index_min + len_compartment])
highest_range = set(ALL[index_max - len_compartment : index_max])
intersection = lowest_range.intersection(highest_range)
if intersection:
# Add the sure candidates to each cell assuming they're present.
self.sure_candidates_by_cross_row[y].update(intersection)
for c in compartment:
# Add the intersection to each cell.
c.sure_candidates_by_row.update(intersection)
# Remove any that aren't possible.
c.sure_candidates_by_row.intersection_update(c.digits)
def _sure_candidates_by_col(self, remove_unusable=False):
for x in ACROSS:
if len(self.compartments_by_col[x]) > 1:
compartment_combinations = []
total_length = 0
for compartment in self.compartments_by_col[x]:
# Generate a sorted list of all the digits used in the compartment.
union = set()
for c in compartment:
union.update(c.digits)
union_list = sorted(union)
# Generate all possible combinations of str8ts for the compartment.
len_compartment = len(compartment)
c_combinations = []
for n in range(1 + len(union_list) - len_compartment):
index_start = ALL.index(union_list[n])
index_end = ALL.index(union_list[n + len_compartment - 1])
if index_end - index_start == len_compartment - 1:
c_combinations.append(set(union_list[n : n + len_compartment]))
# These are stored for each compartment.
compartment_combinations.append(c_combinations)
total_length += len_compartment
# If we have more than 1 compartment we make all the possible combinations that are legal.
col_unions = []
legal_compartments = [[] for c in compartment_combinations]
for combinations in product(*compartment_combinations):
union = set.union(*combinations)
# Is a legal combination
if len(union) == total_length:
# Make a union for the row
col_unions.append(union)
# Add the legal combinations to their compartment lists.
for n, c in enumerate(combinations):
legal_compartments[n].append(c)
col_union = set.intersection(*col_unions)
self.sure_candidates_by_cross_col[x].update(col_union)
for n, legal_unions in enumerate(legal_compartments):
compartment_union = set.union(*legal_unions)
compartment_intersection = set.intersection(*legal_unions)
for c in self.compartments_by_col[x][n]:
if remove_unusable:
for d in c.digits:
if d not in compartment_union:
c.can_not_be(d)
c.sure_candidates_by_col.update(compartment_intersection)
c.sure_candidates_by_col.intersection_update(c.digits)
else:
for compartment in self.compartments_by_col[x]:
union = set()
for c in compartment:
union.update(c.digits)
index_min = ALL.index(min(union))
index_max = ALL.index(max(union)) + 1 # Required for correct range
len_compartment = len(compartment)
lowest_range = set(ALL[index_min : index_min + len_compartment])
highest_range = set(ALL[index_max - len_compartment : index_max])
intersection = lowest_range.intersection(highest_range)
if intersection:
# Add the sure candidates to each cell assuming they're present.
self.sure_candidates_by_cross_col[x].update(intersection)
for c in compartment:
# Add the intersection to each cell.
c.sure_candidates_by_col.update(intersection)
# Remove any that aren't possible.
c.sure_candidates_by_col.intersection_update(c.digits)
######################################################################################################################
def __str__(self):
lines = [" 123456789"]
for y in DOWN:
line = "".join([str(self[x, y]) for x in ACROSS])
lines.append("%s %s" % (y, line))
return "\n".join(lines)
def __repr__(self):
return self._to_string()
def _to_string(self, lean=False, sure_candidates=False):
def _sc(y, sc_attribute):
line = []
for x in ACROSS:
sc = getattr(self[x, y], sc_attribute)
parts = []
for d in ALL:
if d in sc:
parts.append(d)
else:
parts.append(" ")
line.append("".join(parts))
return "│".join(line)
key = "\033[43;30mR\033[100m+\033[46;30mC\033[100m=\033[42;30mB\033[0m"
header = key + " 1 2 3 4 5 6 7 8 9"
top = " \033[40m┌─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┐\033[0m"
divider = " \033[40m├─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┼─────────┤\033[0m"
bottom = " \033[40m└─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┘\033[0m"
lines = [header, top]
for n, y in enumerate(DOWN):
# Help with debugging the tests
if lean:
for x in ACROSS:
if self[x, y].is_white():
break
else:
break
parts = [repr(self[x, y]) for x in ACROSS]
line = "\033[40m│\033[0m".join(parts)
lines.append("%s \033[40m│\033[0m%s\033[40m│\033[0m" % (y, line))
if sure_candidates:
lines.append(" R\033[40m│\033[0m%s\033[40m│\033[0m" % _sc(y, "sure_candidates_by_row"))
lines.append(" C\033[40m│\033[0m%s\033[40m│\033[0m" % _sc(y, "sure_candidates_by_col"))
if n < len(DOWN) - 1:
lines.append(divider)
lines.append(bottom)
return "\n".join(lines)
def _clear_removed(self):
for v in self.values():
v.removed.clear()
def _dump_compartments(self):
lines = []
for x, y in zip(ACROSS, DOWN):
by_row = " ".join(self.compartments_by_row[y])
by_col = " ".join(self.compartments_by_col[x])
lines.append("{}: {:<10} {}: {}".format(y, by_row, x, by_col))
return "\n".join(lines)
def _completeness(self):
completeness = 0
for c in self.values():
if c.is_known():
completeness += 9
else:
completeness += 9 - len(c.digits)
return completeness
class InvalidSolution(Exception):
pass
def _valid(self):
for _, c in self.items():
if c.is_white():
if len(c.digits) == 0:
raise Board.InvalidSolution(x, y, c.digits)
for y in DOWN:
seen = set()
for x in ACROSS:
c = self[x, y]
if c.is_known():
d = c.value()
if d in seen:
raise Board.InvalidSolution(x, y, d)
else:
seen.add(d)
for x in ACROSS:
seen = set()
for y in DOWN:
c = self[x, y]
if c.is_known():
d = c.value()
if d in seen:
raise Board.InvalidSolution(x, y, d)
else:
seen.add(d)
def __eq__(self, other):
for ny, y in enumerate(DOWN):
for nx, x in enumerate(ACROSS):
try:
digits = other[ny][nx]
except:
digits = BLACK
if self[x, y].match(digits):
pass
else:
_fail("{}{} is {} expected {}".format(x, y, "".join(self[x, y].digits), digits))
return False
return True
######################################################################################################################
def remove_used_digits(self):
for (cx, cy), c in self.items():
if c.is_known() and (cx, cy) not in self._known_cells:
cn = c.value()
for x in ACROSS:
self[x, cy].can_not_be(cn)
for y in DOWN:
self[cx, y].can_not_be(cn)
self._known_cells[cx, cy] = c
def compartment_range_check_by_row(self):
for _, compartment in self._iter_compartments_by_row():
compartment_range_check_by_cells(compartment)
def compartment_range_check_by_col(self):
for _, compartment in self._iter_compartments_by_col():
compartment_range_check_by_cells(compartment)
def sure_candidates_by_row(self):
self._sure_candidates_by_row(True)
for y, compartment in self._iter_compartments_by_row():
sure_candidates_by_cells(compartment, [self[x, y] for x in ACROSS], Cell.get_sc_by_row)
def sure_candidates_by_col(self):
self._sure_candidates_by_col(True)
for x, compartment in self._iter_compartments_by_col():
sure_candidates_by_cells(compartment, [self[x, y] for y in DOWN], Cell.get_sc_by_col)
def singles_by_row(self):
for _, compartment in self._iter_compartments_by_row():
singles_by_cell(compartment, Cell.get_sc_by_row)
def singles_by_col(self):
for _, compartment in self._iter_compartments_by_col():
singles_by_cell(compartment, Cell.get_sc_by_col)
def stranded_digits_by_row(self):
for _, compartment in self._iter_compartments_by_row():
stranded_digits_by_cells(compartment)
def stranded_digits_by_col(self):
for _, compartment in self._iter_compartments_by_col():
stranded_digits_by_cells(compartment)
def bridging_digits_by_row(self):
for _, compartment in self._iter_compartments_by_row():
bridging_digits_by_cells(compartment)
def bridging_digits_by_col(self):
for _, compartment in self._iter_compartments_by_col():
bridging_digits_by_cells(compartment)
def stranded_by_bridge_by_row(self):
for _, compartment in self._iter_compartments_by_row():
stranded_by_bridge_by_cells(compartment)
def stranded_by_bridge_by_col(self):
for _, compartment in self._iter_compartments_by_col():
stranded_by_bridge_by_cells(compartment)
def split_compartments_by_row(self):
for _, compartment in self._iter_compartments_by_row():
split_compartments_by_cells(compartment)
def split_compartments_by_col(self):
for _, compartment in self._iter_compartments_by_col():
split_compartments_by_cells(compartment)
def mind_the_gap_by_row(self):
for _, compartment in self._iter_compartments_by_row():
mind_the_gap_by_cells(compartment)
def mind_the_gap_by_col(self):
for _, compartment in self._iter_compartments_by_col():
mind_the_gap_by_cells(compartment)
def mind_the_bridging_gap_by_row(self):
for _, compartment in self._iter_compartments_by_row():
mind_the_bridging_gap_by_cells(compartment)
def mind_the_bridging_gap_by_col(self):
for _, compartment in self._iter_compartments_by_col():
mind_the_bridging_gap_by_cells(compartment)
def naked_groups_by_row(self):
for y in DOWN:
naked_groups_by_cells([self[x, y] for x in ACROSS if self[x, y].is_unknown()])
def naked_groups_by_col(self):
for x in ACROSS:
naked_groups_by_cells([self[x, y] for y in DOWN if self[x, y].is_unknown()])
def hidden_group_by_row(self):
for _, compartment in self._iter_compartments_by_row():
hidden_group_by_cells(compartment, Cell.get_sc_by_row)
def hidden_group_by_col(self):
for _, compartment in self._iter_compartments_by_col():
hidden_group_by_cells(compartment, Cell.get_sc_by_col)
def hidden_group_cross_by_row(self):
for y in DOWN:
hidden_group_by_cross_cells([self[x, y] for x in ACROSS], self.sure_candidates_by_cross_row[y])
def hidden_group_cross_by_col(self):
for x in ACROSS:
hidden_group_by_cross_cells([self[x, y] for y in DOWN], self.sure_candidates_by_cross_col[x])
def sea_creatures_by_row(self):
def _sea_creatures_by_row(d):
hit = False
d_sure_candidates = {}
for y in DOWN:
candidates = set(
[x for x in ACROSS if self[x, y].is_unknown() and d in self[x, y].sure_candidates_by_row]
)
if candidates:
d_sure_candidates[y] = candidates
# ??? Is it better to search from large to small?
for r in range(2, len(d_sure_candidates) + 1):
for combination in combinations(d_sure_candidates, r):
# Merge the combinations
d_sure_union = set()
for c in combination:
d_sure_union.update(d_sure_candidates[c])
if len(d_sure_union) == r:
# We have a sea creature
# We can remove 'd' from all the other rows not included this combination that ..
# ... have 'd's in the union col.
for x in d_sure_union:
self.sure_candidates_by_cross_col[x].add(d)
for y in DOWN:
if y in combination:
assert d in self.sure_candidates_by_cross_row[y]
if d in self[x, y].digits:
assert d in self[x, y].sure_candidates_by_row