-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.py
459 lines (376 loc) · 14 KB
/
script.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
from js import document, alert
import copy
import random
import time
import re
TIME_LIMIT_SECONDS = 1
init = document.getElementById("init")
input = document.getElementById("input")
init.innerHTML = "Enter the desired columns and rows!"
input.style.display = ""
wordlistEl = document.getElementById("word-list")
table = document.getElementById("tableContainer")
def generate():
table.innerHTML = ""
totalRow = document.getElementById("totalRow").value
totalColumn = document.getElementById("totalColumn").value
board = generator(int(totalRow), int(totalColumn))
newtable = '<table>'
for i in range(len(board)):
newtable += '<tr>'
for j in range(len(board[i])):
cell_value = board[i][j]
cell_class = "black" if cell_value == "#" else "white"
newtable += '<td class="' + cell_class + '" style="width:50px;height:50px;" onclick="togglecell(this)">' + cell_value + '</td>'
newtable += '</tr>'
newtable += '</table>'
table.innerHTML = newtable
def solve():
assignment = {}
boardstr = html_table_to_list(table.innerHTML)
words = wordlistEl.value.splitlines()
words = [word.upper() for word in words]
V = create_variables(boardstr, words)
S = create_arc(V)
arc_consistency_3(S)
V.sort(key=lambda x: len(x.domain))
backtrack(V, assignment)
if len(assignment) != len(V):
alert("No solution found!")
return
boardstr = get_final_board(boardstr, assignment)
newtable = '<table>'
for i in range(len(boardstr)):
newtable += '<tr>'
for j in range(len(boardstr[i])):
cell_value = boardstr[i][j]
cell_class = "black" if cell_value == "#" else "white"
newtable += f'<td class="{cell_class}" style="width:50px;height:50px;" onclick="togglecell(this)">{cell_value}</td>'
newtable += '</tr>'
newtable += '</table>'
table.innerHTML = newtable
class Variable:
def __init__(self, direction, row, col, length, domain):
self.word = ""
self.direction = direction
self.row = row
self.col = col
self.length = length
self.domain = set(domain)
self.removed_domain = {}
def html_table_to_list(table_html):
# Extract rows using regular expression
rows_match = re.findall(r'<tr>(.*?)</tr>', table_html, re.DOTALL)
# Extract data from each row
table_data = ""
for i in range(len(rows_match)):
cols_match = re.findall(r'<td(?:\s+.*?)?>(.*?)</td>', rows_match[i], re.DOTALL)
for col_match in cols_match:
table_data += col_match
if i != len(rows_match) - 1:
table_data += "\n"
return table_data
def get_final_board(boardstr, assignment):
final_board = []
board = boardstr.split("\n")
board = [list(row) for row in board]
for v in assignment:
val = assignment[v]
if v.direction == "horizontal":
for i in range(v.length):
board[v.row][v.col + i] = val[i]
else:
for i in range(v.length):
board[v.row + i][v.col] = val[i]
for row in board:
final_board.append(''.join(row))
return final_board
def elapsed_time(start_time):
return time.time() - start_time
def select_unassigned_variable(V, assignment):
unassigned = []
for v in V:
if v not in assignment:
unassigned.append(v)
unassigned.sort(key=lambda x: len(x.domain))
return unassigned[0]
def satisfy_constraint(V, assignment, Vx, val):
for v in V:
Cxv = create_constraint(Vx, v)
if v != Vx and v in assignment and Cxv:
if val[Cxv[0]] != assignment[v][Cxv[1]]:
return False
return True
def backtrack_gen(V, assignment, start_time):
if elapsed_time(start_time) >= TIME_LIMIT_SECONDS:
return False
if len(assignment) == len(V):
return True
Vx = select_unassigned_variable(V, assignment)
for val in Vx.domain:
if val in assignment.values():
continue
if satisfy_constraint(V, assignment, Vx, val):
assignment[Vx] = val
result = backtrack_gen(V, assignment, start_time)
if result:
return True
assignment.pop(Vx, None)
return False
def reduce_domain(V, assignment, Vx, val):
for v in V:
Cxv = create_constraint(Vx, v)
if v != Vx and v not in assignment and Cxv:
elements_to_remove = set()
for word in v.domain:
if val[Cxv[0]] != word[Cxv[1]]:
elements_to_remove.add(word)
v.domain.difference_update(elements_to_remove)
if v not in Vx.removed_domain:
Vx.removed_domain[v] = []
Vx.removed_domain[v].extend(elements_to_remove)
def restore_domain(V, assignment, Vx, val):
for v in V:
Cxv = create_constraint(Vx, v)
if v != Vx and v not in assignment and Cxv:
if v in Vx.removed_domain:
for word in Vx.removed_domain[v]:
if val[Cxv[0]] != word[Cxv[1]]:
v.domain.add(word)
Vx.removed_domain[v] = []
def backtrack(V, assignment):
if len(assignment) == len(V):
return True
Vx = select_unassigned_variable(V, assignment)
for val in Vx.domain:
if val in assignment.values():
continue
if satisfy_constraint(V, assignment, Vx, val):
assignment[Vx] = val
reduce_domain(V, assignment, Vx, val)
result = backtrack(V, assignment)
if result:
return True
assignment.pop(Vx, None)
restore_domain(V, assignment, Vx, val)
return False
def revise(Vx, Vy, Cxy):
if not Cxy:
return False
revised = False
elements_to_remove = set()
for x in Vx.domain:
satisfied = False
for y in Vy.domain:
if x[Cxy[0]] == y[Cxy[1]]:
satisfied = True
break
if not satisfied:
elements_to_remove.add(x)
revised = True
Vx.domain.difference_update(elements_to_remove)
return revised
def arc_consistency_3(S):
for s in S:
X, Y, Cxy = s
revise(X, Y, Cxy)
def create_constraint(Vx, Vy):
constraint = ()
if Vx.direction != Vy.direction:
if Vx.direction == "horizontal":
if Vy.col >= Vx.col and Vy.col <= Vx.col + Vx.length - 1:
if Vx.row >= Vy.row and Vx.row <= Vy.row + Vy.length - 1:
constraint = (Vy.col - Vx.col, Vx.row - Vy.row)
else:
if Vy.row >= Vx.row and Vy.row <= Vx.row + Vx.length - 1:
if Vx.col >= Vy.col and Vx.col <= Vy.col + Vy.length - 1:
constraint = (Vy.row - Vx.row, Vx.col - Vy.col)
return constraint
def create_arc(V):
arcs = []
for i in range(len(V)):
for j in range(i + 1, len(V)):
if i != j:
Cij = create_constraint(V[i], V[j])
if len(Cij) > 0:
arcs.append((V[i], V[j], Cij))
return arcs
def create_variables(boardstr, words):
variables = []
board = boardstr.split("\n")
for row in range(len(board)):
for col in range(len(board[row])):
if board[row][col] != "#":
if col == 0 or board[row][col - 1] == "#":
length = 0
for i in range(col, len(board[row])):
if board[row][i] != "#":
length += 1
else:
break
if length == 1:
cond = True
try:
if board[row][col + 1] != "#":
cond = False
except IndexError:
pass
try:
if board[row][col - 1] != "#" and col - 1 >= 0:
cond = False
except IndexError:
pass
try:
if board[row - 1][col] != "#" and row - 1 >= 0:
cond = False
except IndexError:
pass
try:
if board[row + 1][col] != "#":
cond = False
except IndexError:
pass
if cond:
domain = []
for word in words:
if len(word) == length:
domain.append(word)
variables.append(Variable(
"horizontal",
row,
col,
length,
domain
))
if length > 1:
domain = []
for word in words:
if len(word) == length:
domain.append(word)
variables.append(Variable(
"horizontal",
row,
col,
length,
domain
))
if row == 0 or board[row - 1][col] == "#":
length = 0
for i in range(row, len(board)):
if board[i][col] != "#":
length += 1
else:
break
if length > 1:
domain = []
for word in words:
if len(word) == length:
domain.append(word)
variables.append(Variable(
"vertical",
row,
col,
length,
domain
))
return variables
def get_temp_board(board):
temp_board = ""
for i, row in enumerate(board):
if i == len(board) - 1:
temp_board += ''.join(row)
else:
temp_board += ''.join(row) + "\n"
return temp_board
def is_solveable(board, words):
assignment = {}
boardstr = get_temp_board(board)
V = create_variables(boardstr, words)
S = create_arc(V)
arc_consistency_3(S)
V.sort(key=lambda x: len(x.domain))
start_time = time.time()
result = backtrack_gen(V, assignment, start_time)
if result:
boardstr = get_final_board(boardstr, assignment)
for row in boardstr:
if '-' in row:
return False
return True
else:
return False
def place_word_horizontally(board, length, i, j):
for k in range(length):
board[i][j+k] = '-'
def place_word_vertically(board, length, i, j):
for k in range(length):
board[i+k][j] = '-'
def has_consecutive_chars(lst, char, consecutive_count):
count = 0
for c in lst:
if c == char:
count += 1
if count >= consecutive_count:
return True
else:
count = 0
return False
def is_valid_placement(board, length, i, j, direction):
if direction == "horizontal":
return not has_consecutive_chars(board[i], '-', length)
elif direction == "vertical":
column = [board[x][j] for x in range(i, i + length)]
return not has_consecutive_chars(column, '-', length)
def generate_crossword_board(height, width):
board = [['#' for _ in range(width)] for _ in range(height)]
return board
def add_word_to_board(board, length, position):
max_attempts = 10
direction = "horizontal" if position % 2 == 0 else "vertical"
for _ in range(max_attempts):
i, j = random.choice([(x, y) for x in range(len(board)) for y in range(len(board[0]) - length + 1)]
) if direction == "horizontal" else random.choice([(x, y) for x in range(len(board) - length + 1) for y in range(len(board[0]))])
if is_valid_placement(board, length, i, j, direction):
if direction == "horizontal":
place_word_horizontally(board, length, i, j)
else:
place_word_vertically(board, length, i, j)
break
def find_occupancy(board):
white = 0
black = 0
for row in board:
for c in row:
if c == '-':
white += 1
else:
black += 1
return white / (white + black)
def generator(height, width):
max_attempts = 10
wordlist = wordlistEl.value.splitlines()
occupancy = document.getElementById("occupancy").value
occupancy = float(occupancy) / 100
# #if board height and width is less than 3, then give a board with all -'s
if height <= 3 and width <= 3:
board = [['-' for _ in range(width)] for _ in range(height)]
return board
testing_board = generate_crossword_board(height, width)
while True:
word_length = random.randint(1, min(height, width))
choice = random.randint(1, 2) # vertical or horizontal
final_board = copy.deepcopy(testing_board)
add_word_to_board(testing_board, word_length, choice)
if not is_solveable(testing_board, wordlist):
# try adding the word for 10 times
for _ in range(max_attempts):
testing_board = copy.deepcopy(final_board)
add_word_to_board(testing_board, word_length, choice)
if is_solveable(testing_board, wordlist):
break
else:
if find_occupancy(testing_board) < occupancy:
continue
else:
break
return final_board