-
Notifications
You must be signed in to change notification settings - Fork 0
/
letterboxed.py
211 lines (176 loc) · 7.97 KB
/
letterboxed.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
from webster import WebsterDict
import logging
import datetime
DEBUG = 0
DICTS = ['dictionaries/metamorphosis.json', 'dictionaries/warpeace.json', 'dictionaries/letterboxed.json','dictionaries/webster.json']
def check_solution(letters, solution):
# Check solution- takes a list of letters ['a','s','d',...] and
# proposed solution ['came', 'eyes', 'sales', 'swayed', 'drive']
# and checks to see if the solution contains all characters in the letters array.
if len(solution) == 0:
return False
result = []
for ea in [[y[0] for y in x] for x in letters]:
result += ea
for word in solution:
for letter in word:
if letter in result:
result.remove(letter)
if len(result) == 0:
return True
return False
# # checks to see whether all letters have been hit
# result = []
# for ea in [[y[1] for y in x] for x in letters]:
# result += ea
# return all(result)
def update_letters(letters, pos1, pos2):
# Returns a new letters array with a hit count (Unused, needs replacing) by side and letter index
result = []
for i in range(4):
side = []
for j in range(3):
side.append((letters[i][j][0], letters[i][j][1] + (pos1 == i and pos2 == j)))
result.append(side)
return result
def update_letters_by_value(letters, value):
# Returns a new letters array with a hit count (Unused, needs replacing) by value
result = []
for i in range(4):
side = []
for j in range(3):
side.append((letters[i][j][0], letters[i][j][1] + (letters[i][j][0] == value)))
result.append(side)
return result
def print_box(sides_list_o):
# display the letter boxed game board
sides_list = [[y for y in x] for x in sides_list_o]
SPACERS = 1
print((" " * SPACERS).join([" "] + sides_list[0] + [" "]))
for i in range(0, 3):
print((" " * SPACERS).join([sides_list[3][2 - i]] + [' ', ' ', ' '] + [sides_list[1][i]]))
sides_list[2].reverse()
print((" " * SPACERS).join([" "] + sides_list[2] + [" "]))
def generate_solutions(letters, dictionary, max_word_length, min_word_length, max_solution_steps, pointer=None,
solutions=[], working_solution=[], working_word=''):
if len(working_word) > max_word_length:
# If working word became too long (ie. game dictionary contains extremely long words)
return solutions
if pointer is None:
for side in range(4):
for letter_num in range(3):
# Select starting letter
pointer = dictionary.head
starting_letter = letters[side][letter_num][0]
if pointer.has_child(starting_letter):
pointer = pointer.find_child(starting_letter)
solutions = generate_solutions([[y for y in x] for x in letters], dictionary, max_word_length,
min_word_length, max_solution_steps, pointer=pointer,
solutions=solutions)
logging.info("{:.1f}% complete / {} solutions found / starting letter '{}'".format(100 * (side * 3 + letter_num) / 12, len(solutions), starting_letter))
return solutions
working_word += pointer.value
letter_options = get_valid_options(letters, pointer)
if pointer.is_word and len(working_word) >= min_word_length and working_word not in working_solution:
letters = update_letters_by_value(letters, pointer.value)
working_solution.append(working_word)
if dictionary.head.has_child(pointer.value):
return generate_solutions(letters, dictionary, max_word_length, min_word_length, max_solution_steps,
pointer=dictionary.head.find_child(pointer.value), solutions=solutions,
working_solution=[x for x in working_solution])
return solutions
if check_solution(letters, working_solution):
logging.debug("Found valid solution {}".format(working_solution))
solutions.append(working_solution)
return solutions
else:
if len(working_solution) == max_solution_steps:
# Exceeded max solution size- exit
return solutions
for option in letter_options:
if pointer.has_child(option):
letters = update_letters_by_value(letters, pointer.value)
solutions = generate_solutions(letters, dictionary, max_word_length, min_word_length, max_solution_steps,
pointer=pointer.find_child(option), solutions=solutions,
working_solution=[x for x in working_solution], working_word=working_word)
return solutions
def get_valid_options(letters, pointer):
letter_options = []
side_letters = [''.join([y[0] for y in x]) for x in letters]
for side in side_letters:
if pointer.value not in side:
letter_options += [x for x in side]
return letter_options
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
print("Letter boxed solver")
max_word_length = 18
min_word_length = 3
max_solution_steps = 4
# Character entry
while True:
letters = []
if not DEBUG:
entry = input(
"Enter all characters, with or without spaces\n(clockwise, starting from top left corner)\n > ")
if DEBUG:
entry = 'svc aer wmd yli'
entry = entry.replace(" ", "")
if len(entry) != 12:
print("Invalid entry\n")
continue
# Split box into sides
for i in range(0, 4):
letters.append([x for x in entry[i * 3:((i + 1) * 3)]])
print_box(letters)
if DEBUG or input('Ok? [y/n] > ').lower() == 'y':
break
print(" ")
if DEBUG:
max_solution_steps = 4
else:
try:
max_solution_steps = int(input('Max solution size > '))
except ValueError:
logging.warning("Invalid entry")
max_solution_steps = 4
letters = [[(y, 0) for y in x] for x in letters]
solution = []
for DICT in DICTS:
# time calculation
start_time = datetime.datetime.now()
# load game dictionary
print("\nLoading game dictionary... ({}/{} : {})".format(DICTS.index(DICT) + 1, len(DICTS), DICT.split('/')[-1].split('.')[0]))
mydict = WebsterDict()
mydict.load(DICT)
# prune the tree using the letters
mydict.prune([x for x in entry])
# check number of possible game words for today
game_list = mydict.dump()
# text preview of game words
preview = 'no preview available'
if len(game_list) >= 4:
preview = "{}, {}...{}, {}".format(game_list[0],game_list[1], game_list[-2], game_list[-1])
print("Loaded {} valid dictionary words({})".format(len(game_list), preview))
del preview, game_list
# Now make permutations
# Expand list into tuple
print("Generating solutions...")
solution = generate_solutions(letters, mydict, max_word_length, min_word_length, max_solution_steps, solutions=solution)
solution.sort(key=len)
td = (datetime.datetime.now() - start_time).seconds
timestring=[]
if td // 3600 > 0:
timestring += ['{:d} hr'.format(td // 3600)]
if td % 3600 // 60 > 0:
timestring += ['{:d} min'.format((td % 3600) // 60)]
if td % 3600 % 60 > 0:
timestring += ['{:d} sec'.format(td % 3600 % 60)]
if td == 0:
timestring += ['< 1 sec']
timestring = " ".join(timestring)
print("\nSearch completed in {}".format(timestring))
print("Found {} solutions (shortest length {})".format(len(solution), (len(solution[0]) if len(solution) > 0 else "n/a")))
disp = solution[:min(10, len(solution))]
disp = ",\t\t".join([" -> ".join(x) for x in disp])
print(disp)