-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate.py
More file actions
484 lines (408 loc) · 14.3 KB
/
generate.py
File metadata and controls
484 lines (408 loc) · 14.3 KB
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
import sys
from crossword import *
import random
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def prepend(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def pop_head(self):
first_element = self.head.data
self.delete_node(self.head.data)
return first_element
def insert_after_node(self, prev_node, data):
if not prev_node:
print("Previous node does not exist.")
return
new_node = Node(data)
new_node.next = prev_node.next
prev_node.next = new_node
def delete_node(self, key):
cur_node = self.head
if cur_node and cur_node.data == key:
self.head = cur_node.next
cur_node = None
return
prev = None
while cur_node and cur_node.data != key:
prev = cur_node
cur_node = cur_node.next
if cur_node is None:
return
prev.next = cur_node.next
cur_node = None
def is_empty(self):
if self.head:
return False
else:
return True
# delete a node at a specific location
def delete_node_at_pos(self, pos):
if self.head:
cur_node = self.head
if pos == 0:
self.head = cur_node.next
cur_node = None
return
prev = None
count = 0
while cur_node and count != pos:
prev = cur_node
cur_node = cur_node.next
count += 1
if cur_node is None:
return
prev.next = cur_node.next
cur_node = None
# find the length recursively
def len_recursive(self, node):
if node is None:
return 0
return 1 + self.len_recursive(node.next)
def swap_nodes(self, key_1, key_2):
if key_1 == key_2:
return
prev_1 = None
curr_1 = self.head
while curr_1 and curr_1.data != key_1:
prev_1 = curr_1
curr_1 = curr_1.next
prev_2 = None
curr_2 = self.head
while curr_2 and curr_2.data != key_2:
prev_2 = curr_2
curr_2 = curr_2.next
if not curr_1 or not curr_2:
return
if prev_1:
prev_1.next = curr_2
else:
self.head = curr_2
if prev_2:
prev_2.next = curr_1
else:
self.head = curr_1
curr_1.next, curr_2.next = curr_2.next, curr_1.next
def reverse_iterative(self):
prev = None
cur = self.head
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
self.head = prev
def reverse_recursive(self):
def _reverse_recursive(cur, prev):
if not cur:
return prev
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return _reverse_recursive(cur, prev)
self.head = _reverse_recursive(self.head, None)
def move_tail_to_head(self):
if self.head and self.head.next:
last = self.head
second_to_last = None
while last.next:
second_to_last = last
last = last.next
last.next = self.head
second_to_last.next = None
self.head = last
class CrosswordCreator():
def __init__(self, crossword):
"""
Create new CSP crossword generate.
"""
self.crossword = crossword
self.domains = {
var: self.crossword.words.copy()
for var in self.crossword.variables
}
def letter_grid(self, assignment):
"""
Return 2D array representing a given assignment.
"""
letters = [
[None for _ in range(self.crossword.width)]
for _ in range(self.crossword.height)
]
for variable, word in assignment.items():
direction = variable.direction
for k in range(len(word)):
i = variable.i + (k if direction == Variable.DOWN else 0)
j = variable.j + (k if direction == Variable.ACROSS else 0)
letters[i][j] = word[k]
return letters
def print(self, assignment):
"""
Print crossword assignment to the terminal.
"""
letters = self.letter_grid(assignment)
for i in range(self.crossword.height):
for j in range(self.crossword.width):
if self.crossword.structure[i][j]:
print(letters[i][j] or " ", end="")
else:
print("█", end="")
print()
def save(self, assignment, filename):
"""
Save crossword assignment to an image file.
"""
from PIL import Image, ImageDraw, ImageFont
cell_size = 100
cell_border = 2
interior_size = cell_size - 2 * cell_border
letters = self.letter_grid(assignment)
# Create a blank canvas
img = Image.new(
"RGBA",
(self.crossword.width * cell_size,
self.crossword.height * cell_size),
"black"
)
font = ImageFont.truetype("assets/fonts/OpenSans-Regular.ttf", 80)
draw = ImageDraw.Draw(img)
for i in range(self.crossword.height):
for j in range(self.crossword.width):
rect = [
(j * cell_size + cell_border,
i * cell_size + cell_border),
((j + 1) * cell_size - cell_border,
(i + 1) * cell_size - cell_border)
]
if self.crossword.structure[i][j]:
draw.rectangle(rect, fill="white")
if letters[i][j]:
w, h = draw.textsize(letters[i][j], font=font)
draw.text(
(rect[0][0] + ((interior_size - w) / 2),
rect[0][1] + ((interior_size - h) / 2) - 10),
letters[i][j], fill="black", font=font
)
img.save(filename)
def solve(self):
"""
Enforce node and arc consistency, and then solve the CSP.
"""
self.enforce_node_consistency()
self.ac3()
return self.backtrack(dict())
def enforce_node_consistency(self):
"""
Update `self.domains` such that each variable is node-consistent.
(Remove any values that are inconsistent with a variable's unary
constraints; in this case, the length of the word.)
"""
for variable in self.domains:
words = self.domains[variable].copy()
for word in words:
if len(word) != variable.length:
self.domains[variable].remove(word)
def revise(self, x, y):
"""
Make variable `x` arc consistent with variable `y`.
To do so, remove values from `self.domains[x]` for which there is no
possible corresponding value for `y` in `self.domains[y]`.
Return True if a revision was made to the domain of `x`; return
False if no revision was made.
"""
overlaps = self.crossword.overlaps[x, y]
x_domain = self.domains[x].copy()
y_domain = self.domains[y].copy()
change = False
if overlaps:
x_overlaps = overlaps[0]
y_overlaps = overlaps[1]
for x_word in x_domain:
overlap_letter = x_word[x_overlaps]
conflict = True
for y_word in y_domain:
if y_word[y_overlaps] == overlap_letter and y_word != x_word:
conflict = False
break
if conflict:
self.domains[x].remove(x_word)
change = True
return change
else:
return False
def check(self, x, y, assignment):
if y in assignment:
overlaps = self.crossword.overlaps[x, y]
x_overlap = overlaps[0]
y_overlap = overlaps[1]
x_word = assignment[x]
y_word = assignment[y]
if x_word[x_overlap] == y_word[y_overlap]:
return False
else:
return True
else:
return False
def ac3(self, arcs=None):
"""
Update `self.domains` such that each variable is arc consistent.
If `arcs` is None, begin with initial list of all arcs in the problem.
Otherwise, use `arcs` as the initial list of arcs to make consistent.
Return True if arc consistency is enforced and no domains are empty;
return False if one or more domains end up empty.
"""
queue = LinkedList()
if not arcs:
arcs = self.crossword.overlaps
for i in arcs:
x_and_y = i
overlap = arcs[i]
if overlap:
queue.append((i, overlap))
while not queue.is_empty():
head = queue.pop_head()
x = head[0][0]
y = head[0][1]
overlap = head[1]
if self.revise(x, y):
if len(self.domains[x]) == 0:
return False
else:
for neighbor in self.crossword.neighbors(x):
if neighbor != y:
queue.append(((neighbor, x), overlap))
return True
def assignment_complete(self, assignment):
"""
Return True if `assignment` is complete (i.e., assigns a value to each
crossword variable); return False otherwise.
"""
for key in assignment:
if (not assignment[key]) or (len(assignment[key]) != 1):
return False
return True
def consistent(self, assignment):
"""
Return True if `assignment` is consistent (i.e., words fit in crossword
puzzle without conflicting characters); return False otherwise.
"""
words_array = []
words_set = set()
for var in assignment:
value = assignment[var]
if value:
if len(value) != var.length:
return False
words_array.append(value)
words_set.add(value)
neighbors = self.crossword.neighbors(var)
for neighbor in neighbors:
conflict = self.check(var, neighbor, assignment)
if conflict:
return False
if len(words_array) != len(words_set):
return False
return True
def order_domain_values(self, var, assignment):
"""
Return a list of values in the domain of `var`, in order by
the number of values they rule out for neighboring variables.
The first value in the list, for example, should be the one
that rules out the fewest values among the neighbors of `var`.
"""
final = list()
for var in self.crossword.variables:
if var not in assignment:
pass
def select_unassigned_variable(self, assignment):
"""
Return an unassigned variable not already part of `assignment`.
Choose the variable with the minimum number of remaining values
in its domain. If there is a tie, choose the variable with the highest
degree. If there is a tie, any of the tied variables are acceptable
return values.
"""
possible = []
for var in self.crossword.variables:
if not var in assignment:
possible.append(var)
shortest = float("inf")
for var in possible:
domain = self.domains[var]
if len(domain) < shortest:
shortest = len(domain)
answer = var
tie = []
tie.append(answer)
for var in possible:
if var != answer:
var_domain = self.domains[var]
answer_domain = self.domains[answer]
if len(var_domain) == len(answer_domain):
tie.append(var)
largest = float("-inf")
for var in tie:
neighbors = self.crossword.neighbors(var)
if len(neighbors) > largest:
largest = len(neighbors)
answer = var
return answer
def backtrack(self, assignment):
"""
Using Backtracking Search, take as input a partial assignment for the
crossword and return a complete assignment if possible to do so.
`assignment` is a mapping from variables (keys) to words (values).
If no assignment is possible, return None.
"""
variables = self.crossword.variables
if len(assignment) == len(variables):
return assignment
# Try a new variable
var = self.select_unassigned_variable(assignment)
domains = self.domains[var].copy()
for value in domains:
new_assignment = assignment.copy()
new_assignment[var] = value
if self.consistent(new_assignment):
result = self.backtrack(new_assignment)
if result is not None:
return result
return None
def main(structure, words, output=None):
# Generate crossword
print(words)
crossword = Crossword(structure, words)
creator = CrosswordCreator(crossword)
assignment = creator.solve()
# Print result
if assignment is None:
print("No solution.")
return False
else:
creator.print(assignment)
if output:
creator.save(assignment, output)
return True
if __name__ == "__main__":
main()