Last active
December 14, 2015 09:50
-
-
Save thomasballinger/5067760 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_transitions(n): | |
"""Return a dictionary of array spots to neighbors for an nxn grid""" | |
def neighbors(row, col): | |
return {at(to_row, to_col) | |
for to_row in around(row) | |
for to_col in around(col) | |
if (to_row, to_col) != (row, col)} | |
def at(row, col): | |
return row * n + col | |
def around(i): | |
return range(max(0, i-1), min(i+2, n)) | |
return {at(row, col): neighbors(row, col) | |
for row in range(n) | |
for col in range(n)} | |
dictionary = set(open('/usr/share/dict/words').read().split('\n')) | |
fragments = {word[:i] for word in dictionary for i in range(1, len(word))} | |
def all_words(board): | |
transitions = get_transitions([i for i in xrange(100) if i*i == len(board)][0]) | |
def words(visited, word): | |
if word in dictionary: | |
yield word | |
if word not in fragments: | |
return | |
for pos in transitions[visited[-1]]: | |
if pos in visited: | |
continue | |
for inner_word in words(visited + (pos,), word+board[pos]): | |
yield inner_word | |
for pos in range(len(board)): | |
for word in words((pos,), board[pos]): | |
yield word | |
board = 'abcdefghijklmnop' | |
words = [] | |
for word in all_words(board): | |
words.append(word) | |
print word | |
words = list(set(w for w in all_words(board) if len(w) > 2)) | |
words.sort() | |
print words | |
print len(words), 'unique words of length 3 or more' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice. Just small tweaks.
I changed the prints to run in python3 since I don't have 2.7 installed.
http://stackoverflow.com/questions/746082/how-to-find-list-of-possible-words-from-a-letter-matrix-boggle-solver/750012#750012 was my solution.