Skip to content

Instantly share code, notes, and snippets.

@basicxman
Created April 6, 2012 14:38
Show Gist options
  • Save basicxman/2320447 to your computer and use it in GitHub Desktop.
Save basicxman/2320447 to your computer and use it in GitHub Desktop.
def unique(l):
return list(set(l))
def check(board, needle, path, pos):
if pos[0] < 0 or pos[0] > 3: return False
if pos[1] < 0 or pos[1] > 3: return False
if pos in path: return False
return board[pos[0]][pos[1]] == needle
def search(board, needle, pos, path = []):
if len(needle) == 0: return True
if pos == False:
for x, row in enumerate(board):
for y, cell in enumerate(row):
if cell == needle[0]:
if search(board, needle[1:], (x, y)):
return True
return False
c = (pos[0] - 1, pos[1] - 1)
if check(board, needle[0], path, c):
if search(board, needle[1:], c, path + [c]): return True
c = (pos[0] - 1, pos[1])
if check(board, needle[0], path, c):
if search(board, needle[1:], c, path + [c]): return True
c = (pos[0] - 1, pos[1] + 1)
if check(board, needle[0], path, c):
if search(board, needle[1:], c, path + [c]): return True
c = (pos[0], pos[1] - 1)
if check(board, needle[0], path, c):
if search(board, needle[1:], c, path + [c]): return True
c = (pos[0], pos[1] + 1)
if check(board, needle[0], path, c):
if search(board, needle[1:], c, path + [c]): return True
c = (pos[0] + 1, pos[1] - 1)
if check(board, needle[0], path, c):
if search(board, needle[1:], c, path + [c]): return True
c = (pos[0] + 1, pos[1])
if check(board, needle[0], path, c):
if search(board, needle[1:], c, path + [c]): return True
c = (pos[0] + 1, pos[1] + 1)
if check(board, needle[0], path, c):
if search(board, needle[1:], c, path + [c]): return True
def calculate_score(word):
value = max(1, len(word) - 3)
return 11 if value > 4 else value
def play_boggle(boggle, words):
prev_length = len(words)
words = filter(lambda word: len(word) >= 3, words)
num_illegal_too_short = prev_length - len(words)
prev_length = len(words)
words = unique(words)
num_illegal_duplicates = prev_length - len(words)
score = 0
good = 0
not_found = 0
for word in words:
if search(boggle, word, False):
score += calculate_score(word)
good += 1
else:
not_found += 1
print "Your score: %d (%d good, %d not found, %d too short, %d repeated)" % (score, good, not_found, num_illegal_too_short, num_illegal_duplicates)
data = open("DATA41.txt").readlines()
i = 0
while i < len(data):
boggle = map(lambda l: list(l.strip()), data[i:i+4])
i += 4
num_words = int(data[i])
i += 1
words = []
for x in range(i, i + num_words):
words.append(data[x].strip())
i += num_words
play_boggle(boggle, words)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment