Skip to content

Commit 551fa3a

Browse files
committed
Keep the variable names of Crossword distinct on grids with ten or more rows or columns
The name of a cell was "p" followed by its column and row, so (row 1, column 11) and (row 11, column 1) were both p111 and the CSP merged them; a separator between the two indices keeps them apart.
1 parent f104e03 commit 551fa3a

2 files changed

Lines changed: 17 additions & 3 deletions

File tree

‎aima/csp.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1287,14 +1287,20 @@ class Crossword(NaryCSP):
12871287
writable cell and '*' a blocked cell; each maximal run of two or more cells (across
12881288
or down) becomes a variable sequence constrained to spell one of the given words."""
12891289

1290+
@staticmethod
1291+
def cell(row, col):
1292+
"""Name of the variable of the cell in the given row and column; the separator
1293+
keeps the names distinct once the grid has ten or more rows or columns."""
1294+
return "p" + str(col) + "_" + str(row)
1295+
12901296
def __init__(self, puzzle, words):
12911297
domains = {}
12921298
constraints = []
12931299
for i, line in enumerate(puzzle):
12941300
scope = []
12951301
for j, element in enumerate(line):
12961302
if element == '_':
1297-
var = "p" + str(j) + str(i)
1303+
var = self.cell(i, j)
12981304
domains[var] = list(string.ascii_lowercase)
12991305
scope.append(var)
13001306
else:
@@ -1308,7 +1314,7 @@ def __init__(self, puzzle, words):
13081314
scope = []
13091315
for j, element in enumerate(line):
13101316
if element == '_':
1311-
scope.append("p" + str(i) + str(j))
1317+
scope.append(self.cell(j, i))
13121318
else:
13131319
if len(scope) > 1:
13141320
constraints.append(Constraint(tuple(scope), is_word_constraint(words)))
@@ -1326,7 +1332,7 @@ def display(self, assignment=None):
13261332
if element == '*':
13271333
puzzle += "[*] "
13281334
else:
1329-
var = "p" + str(j) + str(i)
1335+
var = self.cell(i, j)
13301336
if assignment is not None:
13311337
if isinstance(assignment[var], set) and len(assignment[var]) == 1:
13321338
puzzle += "[" + str(first(assignment[var])).upper() + "] "

‎tests/test_csp.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,14 @@ def test_crossword():
554554
assert _complete_and_consistent(crossword, ac_solver(crossword))
555555

556556

557+
def test_crossword_large_grid_names():
558+
# on a 12x12 grid the cells (1, 11) and (11, 1) must be different variables
559+
puzzle = [['_'] * 12 for _ in range(12)]
560+
crossword = Crossword(puzzle, {'a' * 12})
561+
assert len(crossword.variables) == 144
562+
assert Crossword.cell(1, 11) != Crossword.cell(11, 1)
563+
564+
557565
def test_kakuro():
558566
kakuro = Kakuro(kakuro2)
559567
assert _complete_and_consistent(kakuro, ac_solver(kakuro))

0 commit comments

Comments
 (0)